[Tutor] Beginner level: Why doesn't my code work?
Oscar Benjamin
oscar.j.benjamin at gmail.com
Sun May 19 15:16:31 CEST 2013
On 19 May 2013 14:04, Rafael Knuth <rafael.knuth at gmail.com> wrote:
> Hello,
Hello, please post in plain text (not html) in future. Also you should
mention what version of Python you're using as it makes a dfference in
this case.
>
> here's a tiny little program I wrote:
>
> import random
>
> print("""
>
> This is a magic super computer.
>
> He will ask you a couple of questions.
>
> An ultra-complicated algorithm will then figure out what your favorite meal
> is.
>
> """)
>
> name = str(input("What is your name? "))
In Python 3 you should use input(). In Python 2 you should use
raw_input(). I'm guessing that you're using Python 2. In Python 2 the
input() function tries to evaluate whatever the user types in as if it
was Python code. Since Rafael is not a defined variable it fails. The
fix is to use raw_input() which just returns a string.
An alternative fix is to write
input = raw_input
at the top of your script. That way you won't need to change anything
else to have it work with Python 3. In fact if you write it like this
try:
input = raw_input
except NameError:
pass
then it will work in both Python 2 and 3.
> Here's the error message I am getting:
>
> Traceback (most recent call last):
> File "/home/rafael/Documents/3_Tufcik.py", line 13, in <module>
> name = str(input("What is your name? "))
> File "<string>", line 1, in <module>
> NameError: name 'Rafael' is not defined
Oscar
More information about the Tutor
mailing list