Python Calculate the Sum of All Numbers Between 1 and 100

Document 对象参考手册Python3 Examples

We will use Python to write a simple program to calculate the sum of all integers between 1 and 100. This program will use a loop to iterate over all numbers between 1 and 100 and add them together.

Example

# Initialize the sum to 0
total_sum = 0

# Use a for loop to iterate over all integers between 1 and 100
for number in range(1, 101):
    total_sum += number  # Add the current number to the sum

# Output the final sum
print(The sum of all numbers between 1 and 100 is:, total_sum)

Code explanation:

  1. total_sum = 0: We first initialize a variabletotal_sumto 0, which is used to store the accumulated sum.
  2. for number in range(1, 101): Useforloop to iterate 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 numbernumbertototal_sumin.
  4. print("1到100之间所有数的和为:", total_sum): Finally, print the calculated sum.

Output result:

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

Document 对象参考手册Python3 Examples

Other Extensions