tfcgoldfish
tfcgoldfish

Reputation: 21

First python program error message

I tried to write my first python program and I already get an error message. In the textbook introduction to computer science using python i found the following code:

name = input('What is your name? ')
print('Hello', name)
print('Welcome to Python!')

I checked multiple times for errors and I'm quite sure i typed it exactly like the textbook states. I saved the program as MyFirstProgram.py and after that i ran the module (by pressing F5). If i understand correctly the program asks you to fill in a name. So i typed 'John'. But when i did, the following error occurs:

Traceback (most recent call last):
  File "C:/Users/Wout/.ipython/MyFirstProgram.py", line 3, in <module>
    name = input('What is your name? ')
  File "<string>", line 1, in <module>
NameError: name 'John' is not defined

Why is 'John' not defined? Isn't it the purpose of the program to enter any name? Why do i have to define it? I followed the instructions to the letter...

Kind regards

Upvotes: 2

Views: 492

Answers (4)

Johnny
Johnny

Reputation: 512

'John' will work with input (John won't work), however you should use raw_input() like the others said

Upvotes: 0

Nacib Neme
Nacib Neme

Reputation: 889

You are following a textbook for Python 3 but using Python 2. In Python 2, must use raw_input and don't need brackets on print statements.

Upvotes: 0

alecxe
alecxe

Reputation: 473833

You should use raw_input() instead of an input(), since you are on python-2.x:

name = raw_input('What is your name? ')
print('Hello', name)
print('Welcome to Python!')

prints:

What is your name? John
('Hello', 'John')
Welcome to Python!

Upvotes: 1

nneonneo
nneonneo

Reputation: 179392

input, in Python 2, evaluates the input as if it were a snippet of Python code. This is almost never what you want. Use raw_input instead.

By the way, you're writing your code as if it were Python 3, but you appear to be using a Python 2 interpreter. If you run your code with Python 3, it will work fine (input in Python 3 is the same as raw_input in Python 2).

Upvotes: 2

Related Questions