Python Forum
Summing a list of numbers - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/Forum-Python-Coding)
+--- Forum: General Coding Help (https://python-forum.io/Forum-General-Coding-Help)
+--- Thread: Summing a list of numbers (/Thread-Summing-a-list-of-numbers)



Summing a list of numbers - Oldman45 - Jul-12-2020

I am teaching myself Python and following a YouTube tutorial I input the following:

xs = [12, 14, 10]

for num in xs:
    x += num

print(x)
This works in the tutorial and sums the list to 36, but on my Python I get the following error message:

Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> 
= RESTART: C:/Users/John/Documents/John''s files/Work/Coding/Think Like a Computer Scientist/Programmes/loop_exercise2a.py
Traceback (most recent call last):
  File "C:/Users/John/Documents/John''s files/Work/Coding/Think Like a Computer Scientist/Programmes/loop_exercise2a.py", line 4, in <module>
    x += num
NameError: name 'x' is not defined
>>> 
I would appreciate any advice or help.

Thank you


RE: Summing a list of numbers - Yoriz - Jul-12-2020

In the tutorial, they must have defined x to 0
x = 0
xs = [12, 14, 10]
 
for num in xs:
    x += num
 
print(x)
Output:
36



RE: Summing a list of numbers - palladium - Jul-12-2020

You need to assign x to a value first. Try:

xs = [12, 14, 10]
x = 0
for num in xs:
    x += num

print(x)
Or you can just use the sum function:

xs = [12, 14, 10]
x = sum(num for num in xs)
print(x)



RE: Summing a list of numbers - Yoriz - Jul-12-2020

(Jul-12-2020, 01:25 PM)palladium Wrote: Or you can just use the sum function:

xs = [12, 14, 10]
x = sum(num for num in xs)
print(x)

xs is already a list num for num in xs is making a list from a list

x = sum(xs)
is all that's needed.


RE: Summing a list of numbers - palladium - Jul-12-2020

Thanks for pointing that out. I'm still quite new myself, haha.


RE: Summing a list of numbers - sridhar - Jul-12-2020

You must declare x previously so that you can run without not defined error.

Or you can try this simple sum function

xs = [12, 14, 10]
x = sum(xs) 
print(x)



RE: Summing a list of numbers - Oldman45 - Jul-12-2020

Greetings Yoriz, Palladium and Sridhar

Thank you all for the education - very useful.

Yoriz, apologies for not complying with the rules. I have taken a copy of your link and next time I will comply.

Sridhar I rated Yoriz and Palladium but the system said I had used my ratings up for the day when I tried to rate you so sorry.

Thanks to you all again