3

I got a python code from some book like below, but it runs abnormally.

# name.py

name = input('What is your first name? ')
print('Hello ' + name.capitalize() + '!')

The result is:

$ python name.py
What is your first name? jack
Traceback (most recent call last):
  File "name.py", line 3, in <module>
    name = input('What is your first name? ')
  File "<string>", line 1, in <module>
NameError: name 'jack' is not defined

What is wrong with it? Thanks!

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
Tom Xue
  • 3,169
  • 7
  • 40
  • 77
  • It is perfectly running at my end. Which python version you are using? – Amit Sharma Dec 20 '14 at 05:05
  • I forgot to mention the Python version. The book uses python 3 while I use python 2.7, this may cause the problem. @AmitSharma – Tom Xue Dec 20 '14 at 05:07
  • Yes!! that is why you are facing the problem. `raw_input()` does not exist in Python 3.x, while `input()` does. You can just assume that old `raw_input()` has been renamed to `input()`. They both are same. – Amit Sharma Dec 20 '14 at 05:10

2 Answers2

7

Because it's how input works. See https://docs.python.org/2/library/functions.html#input You have to use raw_input instead.

Pavel Reznikov
  • 2,968
  • 1
  • 18
  • 17
6

That book is written for Python 3. The old Python 2 input() function works differently to the Python 3 input(). As mentioned in the docs linked by troolee, Python 2 input() is equivalent to eval(raw_input(prompt)), which is convenient, but can also be dangerous since any input string is evaluated.

So to run Python 3 code examples on Python 2 you need to replace input() calls with raw_input().

There are other differences that will cause Python 3 code to not work (or at least work differently) on Python 2. In particular, the old print statement no longer exists in Python 3, it's been replaced by a print() function. Some Python 3 print() function calls will work on Python 2, but some won't.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182