KabbageKobra
KabbageKobra

Reputation: 43

Python: NameError in a very simple program

I was working with a for loop to make a super-simple program using for loops that asks you for your hobby three times and appends your answers to a list called hobbies:

hobbies = []

for me in range(3):
    hobby=input("Tell me one of your hobbies: ")
    hobbies.append(hobby)

If I, for example, give it 'coding', it will return:

Traceback (most recent call last):
  File "python", line 4, in <module>
  File "<string>", line 1, in <module>
NameError: name 'coding' is not defined

Note that if I use Python 2.7 and use raw_input instead, the program works beautifully.

Upvotes: 0

Views: 141

Answers (1)

miku
miku

Reputation: 188144

In Python 2 input will evaluate the given string, whereas raw_input will return just a string. Note that in Python 3, raw_input is renamed to input and the old input is only available in the form eval(input()).

Example in Python 2:

In [1]: x = 2

# just a value
In [2]: x ** input("exp: ")
exp: 8
Out[2]: 256

# refering to some name within
In [3]: x ** input("exp: ")
exp: x
Out[3]: 4

# just a function
In [4]: def f():
   ...:     print('Hello from f')
   ...:

# can trigger anything from the outside, super unsafe
In [5]: input("prompt: ")
prompt: f()
Hello from f

Upvotes: 1

Related Questions