Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sum of List
#1
Hi,

I have wrote a python program to sum the numbers in a list.However its giving answer one.

Please advise.

MyList = []
Number =  int(input("Please enter number:"))
for i in range(1, Number + 1):  
    value = int(input("Enter Numbers %d:" %i))
MyList.append(value)

total = sum(MyList)

print("Sum of num:", total)
output

[C:\Practice>py Sumlist.py
Please enter number:4
Enter Numbers 1:1
Enter Numbers 2:2
Enter Numbers 3:3
Enter Numbers 4:1
Sum of num: 1
Reply
#2
just do this
total = 0
for x in MyList:
    total += x
Reply
#3
MyList.append(value) is not inside of the for loop
Reply
#4
(Jul-07-2019, 04:33 PM)SheeppOSU Wrote: just do this
total = 0
for x in MyList:
    total += x

Is not Pythonic. You're doing it wrong.
Also sum is much faster because it's implemented in C.
If you have a very long list, the for-loop is much slower.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
Hi All,

I have done slight modification in code and its working. Thanks all for the response.

MyList = []
Number =  int(input("Please enter number:"))
for i in range(1, Number + 1): 
    value = int(input("Enter Numbers:")) 
    MyList.append (value)
    total = sum(MyList)

print("Sum of num:", total)
output

Please enter number:5
Enter Numbers:5
Enter Numbers:2
Enter Numbers:3
Enter Numbers:5
Enter Numbers:5
Sum of num: 20
Reply
#6
total = sum(MyList) does not need to be in the for loop, this means it calculates the sum for every loop, the sum is only required after the loop has finished.
Reply
#7
Some additional nitpicking as well Smile

It's always good idea to stick naming conventions defined in PEP8.

So instead MyList use my_list (BTW - my_list is not very good name as it doesn't give any hint what list it is and for what purpose it will be used, 'numbers' could be better, especially if you use 'number' as variable name: you append number to numbers numbers.append(number))

Same applies to uppercase 'Number' (use number).

If using 3.6 <= Python then using f-strings is recommended:

print(f'Sum of numbers: {sum(numbers)}')
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020