简体   繁体   中英

Get sum of numbers using a Function and For Loop

I want to define a function, sumAll(n) that sums all numbers from 1 to n .

For example, when I call sumAll(10) should return the answer 55 ...

Because:

1+2+3+4+5+6+7+8+9+10 = 55

The function sumAll needs to use a for loop to carry out this summation, and it will have to use a sum variable that increases in value over each iteration of the for loop.

I have a working function that does not use a for loop, but I need to know how to use a for loop to accomplish this as well.

Here is the working program:

def sumAll(n):
    if n == 0:
        return 0

    return n + sumAll(n - 1)

number = int(raw_input("Please enter a number: \n"))

print ("The answer is: ") + str(sumAll(number))

How do I use a "for" loop to accomplish this? Am I right in assuming the "for loop" should be nested in the "sumAll" function?

I have tried many times to do this using a for loop and I keep getting a infinite result and errors ...

Here is my code:

def sumAll(n):
    y = n + sumAll(n -1)
    return y

num = int(raw_input("Please enter a number")
for n in range(num):
    num = sumAll(num)
    print num

By for loop

def sumAll(n):
    sum_all = 0
    for i in range(1, n+1):
        sum_all = sum_all + i
    return sum_all

number = int(raw_input("Please enter a number: \n"))

print ("The answer is: ") + str(sumAll(number))

Output:

Please enter a number: 
10
The answer is: 55

You can also use list Comprehension :

print sum([i for i in range(number+1)])

Output:

55

You can also use a mathematical series formula:

def sumAll(n):
    return n * (n + 1) / 2   

you can even do it without a loop:

def sumAll(n):
    return  sum(range(1,n+1))

print(sumAll(10)) # -> 55

if you insist on using a loop:

def sumAll(n):
    s = 0
    for i in range(1,n+1):
        s += i
    return s

but the mathematical solution is simply:

def sumAll(n):
    return n * (n + 1) / 2  
    # in python 3:
    # return n * (n + 1) // 2

(there are n elements with an average value of (n+1)/2 ; this will always be an integer since either n or n+1 is even; the proof by induction is often the first example when math students learn about induction...).

You will get an error with sum(1, 2, 3, 4)
TypeError: sum expected at most 2 arguments, got 4

sum((1, 2, 3, 4)) # works cuz tuple inside
sum([1, 2, 3, 4]) # works cuz list inside

so the func will need to gather elements into a tuple, eg

numbers = 1, 2, 3, 4
print(sum(numbers)) # already a tuple so works

use * with your parameter to gather the caller's args into a tuple. * enabbles any-number of args to be supplied by caller and they are converted into a tuple parameter.

def sumall(*args):
    return sum(args)
print(sumall(1))
print(sumall(1, 2))
print(sumall(1, 2, 3))
print(sumall(1, 2, 3, 4))

produces the expected answers. Credit: author Downey asks for this exercises solution in chapter 12 of Think Python (2016)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM