Python - Calculate the Sum of Squares of All Odd Numbers from 1 to 100
We need to write a Python program to calculate the sum of squares of all odd numbers from 1 to 100. We can use loops and conditional statements to implement this functionality.
Example
total_sum = 0
for i in range(1, 101):
if i % 2 != 0:
total_sum += i ** 2
print("The sum of squares of all odd numbers from 1 to 100 is:", total_sum)
for i in range(1, 101):
if i % 2 != 0:
total_sum += i ** 2
print("The sum of squares of all odd numbers from 1 to 100 is:", total_sum)
Code analysis:
total_sum = 0: Initialize a variabletotal_sumUsed to store the sum of squares of all odd numbers.for i in range(1, 101): UseforLoop to iterate through all integers from 1 to 100.if i % 2 != 0: UseifStatement to check whether the current numberiIs an odd number.i % 2 != 0Indicates thatiThe remainder when divided by 2 is not 0, that is,iIt is an odd number.total_sum += i ** 2: IfiIs odd, then calculate its square and add it tototal_sum.print("1到100的所有奇数的平方和为:", total_sum): Finally output the sum of squares of all odd numbers.
Output result:
1到100的所有奇数的平方和为: 166650Other extensions
Python3 Examples