Python Calculate the Sum of All Numbers in a List

Document 对象参考手册Python3 Examples

We will write a Python program to calculate the sum of all numbers in a list. This program will iterate over each element in the list, accumulate them, and finally output the sum.

Examples

def calculate_sum(numbers):
    total = 0
    for num in numbers:
        total += num
    return total

# Example list
numbers = [1, 2, 3, 4, 5]

# Call the function and print the result
result = calculate_sum(numbers)
print("The sum of all numbers in the list is:", result)

Code explanation:

  1. calculate_sumThe function accepts a listnumbersas a parameter.
  2. Initialize a variabletotalto 0, used to store the accumulated result.
  3. Usefora loop to iterate through each element in the listnum。
  4. In each iteration, the current elementnumis added tototalthe total.
  5. After the loop ends, returntotalas the result.
  6. The example listnumberscontains numbers 1 to 5.
  7. Callcalculate_sumthe function and store the result inresultthe variable.
  8. Finally, print the result.

Output result:

列表中所有数字的总和是: 15

Document 对象参考手册Python3 Examples

Other extensions