Python Compute the Sum of All Numbers from 1 to 100
We will write a simple Python program to compute the sum of all integers from 1 to 100. The program uses a loop to iterate over all the numbers from 1 to 100 and accumulate them.
Example
Initialize the total to 0
total_sum
=
0
Use a for loop to iterate over all integers from 1 to 100
for
number
in
range
(
1
,
101
)
:
total_sum +
=
number
Add the current number to the total
Print the final total
(
"The sum of all numbers from 1 to 100 is:"
,
total_sum
)
Code analysis:
total_sum = 0: We first initialize a variabletotal_sumto 0 to store the accumulated total.for number in range(1, 101): When usingforThe loop iterates over all integers from 1 to 100.range(1, 101)Generate a sequence of integers from 1 to 100.total_sum += number: In each iteration, add the current numbernumbertototal_sumit.print("1到100之间所有数的和为:", total_sum): Finally, print the computed total.
Output result:
1到100之间所有数的和为: 5050
Python3 Examples