For a given list, get the sum of each number in the list
Should be simple for you. Declare a sum variable. Then just loop through the list and add it to the sum.
def get_sum(nums):
sum = 0
for num in nums:
sum = sum + num
return sum
nums = [13,89,65,42,12,11,56]
total = get_sum(nums)
print("The total of each elements:",total)
It’s super simple.
You got a list. Loop through the list. You have done that multiple times while learning Fundamentals.
Declare a variable named sum before the loop. And inside the loop, add the number to the sum variable.
And then finally return the sum.
That’s it. Super easy. Even your grandma can do it.
There is an easier way to get sum of all numbers in a list. You can just pass the list of numbers to the sum function.
nums = [13, 11, 16, 78, 31, 128]
total = sum(nums)
print(total)
What is the shortcut way to sum all the numbers in a list?
- Loop through the items
- Use the sum function
- Use a calculator
Show Answer
The answer is : 2
Use the sum function to sum all the numbers in a list.
tags: programming-hero
python
python3
problem-solving
programming
coding-challenge
interview
learn-python
python-tutorial
programming-exercises
programming-challenges
programming-fundamentals
programming-contest
python-coding-challenges
python-problem-solving