Nameerror when entering the value read by the input function

Asked

Viewed 39 times

0

I’m running version 2.7 of Python:

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

When I try to spin that code line:

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

I have the following mistake:

$ 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

Someone knows how I fix it?

1 answer

1


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

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

Take this example:

a = 5
b = 6
c = 7

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

See working on Repl.it

If you enter with the values a, b or c in the input, the result will be something like Seja bem-vindo, 5, because he will evaluate the entrance a for the object of the same name.

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

  • your code worked. I’ll update.

  • yes... I was only waiting for the minimum time of 7 min. You replied before.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.