Hello everyone I'm having trouble with this program in Python called sumList(nums). I already tried to program it, but I get the incorrect output. The program is suppose to get the summ of numbers entered into a list by the user. Mine does not return the sum just the first number in the list. Can someone look at my code and run it to see what is wrong, and then tell me how to fix it. I'm using python3.4.3. The help would be appreciated.

This defines the sumList function.

def sumList(nums):

    ListTotal = 0


for i in nums:
    ListTotal = ListTotal+i
    return ListTotal
Get the input from the user

def main():

    print("This is a program that gathers the sum of all numbers entered into the list.") 


nums = input("Please enter different numbers separated by a comma: ")
nums = nums.split(',')

#The loop counts through number of enties by the user and turns them into a list.
ListEntry = 0
for i in nums:
    nums[ListEntry] = int(i)
    ListEntry = ListEntry+1

SumTotal = sumList(nums)

    # provides the sum of the numbers in the list. This gives the user output.
print('\The sum of the numbers in the list is {}.' .format(SumTotal))

main()

Recommended Answers

All 4 Replies

At first glance it is a problem with indentation in your function. Move the return out of the for loop.

Thanks vegaseat that helped. I'm new to Python so I'm going to make a lot of mistakes like that.

Use an initialized list variable, ListTotal = [] then use append in your loop: ListTotal.append(int(i)) to put each newly converted int number in the list.

Instead of running another loop to sum things, do it as you go with another initialized variable: v_Sum = 0 and then after the list append do this: v_Sum = v_Sum + int(i)

You can then forgo the other function/loop.

The the resulting code could then be packed into a function if needed.

I hope this helped.

By the way, you can split on more than one entry pattern to allow for mistakes by the user. I do this for my factoring program, as I always seemed to enter the wrong pattern, and so just found how to except them all.

nums = input("Please enter different numbers seperated by comma, star, or space: ").replace("*", ",").replace(" ", ",").split(',')

replace does that for each spacer type, putting in a comma for each. Then split does away with the commas. You can add, or subtract "replace" statements as needed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.