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

Python Calculate the Sum of All Numbers in a List

Python Calculate the Sum of All Numbers in a List

Document Object Reference Manual 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.

Example

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 analysis:

  1. calculate_sum The function takes a list numbers as its argument.
  2. Initialize a variable total to 0, used to store the accumulated result.
  3. Use for Loop through each element in the list num。
  4. In each iteration, add the current element num to total .
  5. After the loop ends, return total as the result.
  6. Example list numbers contains the numbers 1 to 5.
  7. called calculate_sum function and store the result in result variable.
  8. Finally, print the result.

Output result:

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

Document Object Reference Manual Python3 Examples