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.
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)
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:
calculate_sumThe function accepts a listnumbersas a parameter.- Initialize a variable
totalto 0, used to store the accumulated result. - Use
fora loop to iterate through each element in the listnum。 - In each iteration, the current element
numis added tototalthe total. - After the loop ends, return
totalas the result. - The example list
numberscontains numbers 1 to 5. - Call
calculate_sumthe function and store the result inresultthe variable. - Finally, print the result.
Output result:
列表中所有数字的总和是: 15Other extensions
Python3 Examples