Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

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

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

Document Object Reference Manual Python3 Examples

We need to write a Python program to compute the sum of squares of all odd numbers from 1 to 100. We can use loops and conditional statements to implement this.

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 variable total_sum to store the sum of squares of all odd numbers.
  2. for i in range(1, 101): When using for Loop through all integers from 1 to 100.
  3. if i % 2 != 0: When using if statement checks the current number i to see whether it is odd.i % 2 != 0 indicates i The remainder of division by 2 is not 0, i.e., i is odd.
  4. total_sum += i ** 2: If i is odd, compute its square and add it to total_sum it.
  5. print("1到100的所有奇数的平方和为:", total_sum): Finally, output the sum of squares of all odd numbers.

Output result:

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

Document Object Reference Manual Python3 Examples