Home > Back-end >  How to sum all the answers from for loop?
How to sum all the answers from for loop?

Time:01-03

Well I'm quite new to python and I'm struggling with this at the moment. I need to sum up all the answers(returns) from this for loop but I don't really know how to do this.

a = int(input('Enter a number plz '))
for i in range(1, a 1):
    def func(root):
        print('Number', i, 'in square root is', root)
    func(i*i)

CodePudding user response:

This can be expressed using a list comprehension and the sum function:

a = int(input('Enter a number plz '))
print(sum(x*x for x in range(a 1)))

Expanded out, this would be equivalent to:

a = int(input('Enter a number plz '))
total = []
for x in range(a 1):
    total.append(x*x)
print(sum(x))

CodePudding user response:

Here's a simpler solution:

a = int(input('Enter a number plz '))
lst = []
for i in range(1, a 1):
    def func(root):
        print('Number', i, 'in square root is', root)
        lst.append(root)
    func(i*i)

print(f'The sum is {sum(lst)}')

You can create an empty list, then append all the values of root as you iterate through the for-loop. Now we have a list of all of the root values, so we can make use of the built-in sum function to achieve our final product.

Also note that it is not necessary to have your function in the for-loop:

a = int(input('Enter a number plz '))

def func(root):
        print('Number', i, 'in square root is', root)
        lst.append(root)
        
lst = []
for i in range(1, a 1):
    func(i*i)

print(f'The sum is {sum(lst)}')

CodePudding user response:

The next code should solve a problem:

a = int(input('Enter a number plz '))
s = 0
for i in range(1, a 1):
    def func(root):
        print('Number', i, 'in square root is', root)
        return root
    s  = func(i*i)
print("The sum is "   str(s))

CodePudding user response:

you can do like this

from math import sqrt
a = int(input('Enter a number plz '))
lst = []
for i in range(1, a 1):
    print('Number', i, 'in square root is ' str(i**2))
    lst.append(i**2)
print("the list for this is " ''.join(lst))
print("the sum of all the squares is " sum(lst))
  • Related