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

Python Compute the Sum of All Numbers from 1 to 100

Python Compute the Sum of All Numbers from 1 to 100

Document Object Reference Manual Python3 Examples

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

print

(

"The sum of all numbers from 1 to 100 is:"

,

total_sum

)

Code analysis:

  1. total_sum = 0: We first initialize a variable total_sum to 0 to store the accumulated total.
  2. for number in range(1, 101): When using for The loop iterates over all integers from 1 to 100.range(1, 101) Generate a sequence of integers from 1 to 100.
  3. total_sum += number: In each iteration, add the current number number to total_sum it.
  4. print("1到100之间所有数的和为:", total_sum): Finally, print the computed total.

Output result:

1到100之间所有数的和为: 5050

Document Object Reference Manual Python3 Examples