Python Compute the Sum of Squares of All Odd Numbers from 1 to 100
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
(
"The sum of squares of all odd numbers from 1 to 100 is:"
,
total_sum
)
Code analysis:
total_sum = 0: Initialize a variabletotal_sumto store the sum of squares of all odd numbers.for i in range(1, 101): When usingforLoop through all integers from 1 to 100.if i % 2 != 0: When usingifstatement checks the current numberito see whether it is odd.i % 2 != 0indicatesiThe remainder of division by 2 is not 0, i.e.,iis odd.total_sum += i ** 2: Ifiis odd, compute its square and add it tototal_sumit.print("1到100的所有奇数的平方和为:", total_sum): Finally, output the sum of squares of all odd numbers.
Output result:
1到100的所有奇数的平方和为: 166650
Python3 Examples