简体   繁体   中英

I can't seem to get this function to add the list together

I'm trying to find a way to add up a list of numbers without using the sum function. I'm a little new to this and so far this is what I've got:

def findSum(nbr_list):
    total = 0
    nbr_list = []
    for nbr in nbr_list:
        total = total + nbr
    print 'Total: ', total

In [32]: nbr_list = [1,2,3,4,100]

In [33]: findSum(nbr_list)
Total:  0

The problem is that you are redefining nbr_list on this line:

nbr_list = []

Doing this causes nbr_list to no longer refer to the [1,2,3,4,100] list that you passed into the function but rather the empty list [] . This means that the for-loop will be iterating over an empty list and total will never be incremented. Thus, 0 is printed because that is the initial value of total .

Simply removing that line makes your function work fine:

>>> def findSum(nbr_list):
...     total = 0
...     for nbr in nbr_list:
...         total += nbr  # Same as 'total = total + nbr'
...     print 'Total: ', total
...
>>> nbr_list = [1,2,3,4,100]
>>> findSum(nbr_list)
Total:  110
>>>

Also, you usually do not want to make your functions print a value and not return anything. A better approach would be to have findSum return total and then print the result of calling the function:

def findSum(nbr_list):
    total = 0
    for nbr in nbr_list:
        total += nbr
    return total

nbr_list = [1,2,3,4,100]
print 'Total: ', findSum(nbr_list)

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