Python - Calculate the Sum of Squares of All Odd Numbers from 1 to 100

Document 对象参考手册Python3 Examples

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)

Code analysis:

  1. total_sum = 0: Initialize a variabletotal_sumUsed to store the sum of squares of all odd numbers.
  2. for i in range(1, 101): UseforLoop to iterate through all integers from 1 to 100.
  3. 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.
  4. total_sum += i ** 2: IfiIs odd, then calculate its square and add it tototal_sum.
  5. print("1到100的所有奇数的平方和为:", total_sum): Finally output the sum of squares of all odd numbers.

Output result:

1到100的所有奇数的平方和为: 166650

Document 对象参考手册Python3 Examples

Other extensions