Python Calculate the Sum of All Numbers in a List
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
)
(
"The sum of all numbers in the list is:"
,
result
)
Code analysis:
calculate_sumThe function takes a listnumbersas its argument.- Initialize a variable
totalto 0, used to store the accumulated result. - Use
forLoop through each element in the listnum。 - In each iteration, add the current element
numtototal. - After the loop ends, return
totalas the result. - Example list
numberscontains the numbers 1 to 5. - called
calculate_sumfunction and store the result inresultvariable. - Finally, print the result.
Output result:
列表中所有数字的总和是: 15
Python3 Examples