Skip to content

Latest commit

 

History

History
67 lines (46 loc) · 1.74 KB

File metadata and controls

67 lines (46 loc) · 1.74 KB

Sum of Elements

The problem

For a given list, get the sum of each number in the list

Hints

Should be simple for you. Declare a sum variable. Then just loop through the list and add it to the sum.

Solution

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)

Try it on Programming Hero

Explanation

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.

Shortcut

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)

Quiz

What is the shortcut way to sum all the numbers in a list?

  1. Loop through the items
  2. Use the sum function
  3. Use a calculator
Show Answer

The answer is : 2

Take Away

Use the sum function to sum all the numbers in a list.

  Next Page  

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