w3resource

Python Exercise: Find the sum of all the numbers in a list


2. Sum All Numbers in a List

Write a Python function to sum all the numbers in a list.

Sample Solution:

Python Code:

# Define a function named 'sum' that takes a list of numbers as input
def sum(numbers):
    # Initialize a variable 'total' to store the sum of numbers, starting at 0
    total = 0
    
    # Iterate through each element 'x' in the 'numbers' list
    for x in numbers:
        # Add the current element 'x' to the 'total'
        total += x
    
    # Return the final sum stored in the 'total' variable
    return total

# Print the result of calling the 'sum' function with a tuple of numbers (8, 2, 3, 0, 7)
print(sum((8, 2, 3, 0, 7))) 

Sample Output:

20

Explanation:

In the exercise above the code defines a function named "sum()" that takes a list of numbers as input and returns the sum of all the numbers in the list. The final print statement demonstrates the result of calling the "sum()" function with a tuple containing the numbers (8, 2, 3, 0, 7).

Pictorial presentation:

Python exercises: Find the sum of all the numbers in a list.

Flowchart:

Flowchart: Python exercises: Find the the sum of all numbers in a list.

For more Practice: Solve these Related Problems:

  • Write a Python function that uses a for-loop to sum all numbers in a list and returns the total.
  • Write a Python function that uses recursion to compute the sum of all elements in a list.
  • Write a Python function that uses the built-in sum() function to sum a list, then compare its output with a manually computed sum.
  • Write a Python function that sums only the positive numbers from a list and ignores negatives, using list comprehension.

Go to:


Previous: Write a Python function to find the Max of three numbers.
Next: Write a Python function to multiply all the numbers in a list.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.