NameError when entering the value read by the input function

0

I'm running Python version 2.7:

Python 2.7.12 (default, Dec  4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2

When I try to run this line of code :

x = input('Enter your name:')
print('Hello, ' + x)

I have the following error:

$ python index.py
Enter your name:acb
Traceback (most recent call last):
  File "index.py", line 1, in <module>
    x = input('Enter your name:')
  File "<string>", line 1, in <module>
NameError: name 'acb' is not defined

Does anyone know how to solve this?

    
asked by anonymous 18.08.2018 / 00:23

1 answer

1

The problem is that you are using the input function in Python 2.7 without apparently knowing how it works.

In this release, the input function will evaluate the input as a Python code. If you type "Generic" and there is no Generic object in context, it will give the name error, as in your example.

See this example:

a = 5
b = 6
c = 7

nome = input('Seu nome (digite a, b ou c): ')
print('Seja bem-vindo, ', nome)

See working at Repl.it

If you enter the values a , b or c into input , the result will be something like Seja bem-vindo, 5 , since it will evaluate the a entry for the object of the same name. / p>

So if you need to stay in version 2.7 of Python, use the raw_input function, or, if possible, migrate to a newer version of Python - the most current one at the moment is 3.7.     

18.08.2018 / 00:28