ding van
ding van

Reputation: 315

NameError about not defined

abc_str = raw_input('A B C: ')
print abc_str
abc_list = abc_str.split()
print abc_list
# suuuum = 0
for i in range(3):
    suuuum += int(abc_list[i])
print suuuum

Traceback (most recent call last):
  File "tttest.py", line 7, in <module>
    suuuum += int(abc_list[i])
NameError: name 'suuuum' is not defined

If I omit the sharp, everything will be ok. But why should I define "suuuum" first? My answer is because I called "suuuum" before I assign it to an object. Then I tried a += 8 in Terminal,as followed:

>>> a += 8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

This is my thought. Am I right?

Upvotes: 1

Views: 79

Answers (1)

EbraHim
EbraHim

Reputation: 2359

You are right. When you write x += 1, it means as below :

x = x + 1

So, if you didn't defined x already, you got an error. Because the interpreter can't calculate the right side of equal.

In your program above, when you commented suuuum, you got the error because you have the following:

for i in range(3):
    suuuum = suuuum + int(abc_list[i])

And thus for the first i, the suuuum in the right side is undefined.

Upvotes: 1

Related Questions