Python input () output is undefined

I got python code from some book like below but it doesn't work normally.

# name.py

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

      

Result:

$ 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's bad about it? Thank!

+3


source to share


2 answers


Because it works input

. See https://docs.python.org/2/library/functions.html#input You should use instead raw_input

.



+7


source


This book is written for Python 3. The old Python 2 feature input()

works differently with Python 3 input()

. As mentioned in the troolee linked docs, Python 2 is input()

equivalent eval(raw_input(prompt))

, which is handy, but can also be dangerous since every input string is evaluated.

So, to run Python 3 code examples in Python 2, you need to replace the calls input()

with raw_input()

.



There are other differences that will cause Python 3 code not to work (or at least work differently) in Python 2. In particular, the old operator print

no longer exists in Python 3, it has been replaced by the print()

function ... Some Python 3 print()

function calls will work on Python 2, but some won't.

+4


source







All Articles