pythoninput

Input() function in Python is not working


I'm new to Python, and I'm trying to compile a VERY simple code in Python (using Atom editor), and after I run this code:

name = input("Name:")
print(f"hello, {name}")

And after typing in any name (in this case I simply typed in n, I get this error message:

Name:n

Traceback (most recent call last):
  File "hello_name.py", line 1, in <module>
    name = input("Name:")
  File "<string>", line 1, in <module>
NameError: name 'n' is not defined

I hope you can help! Thanks!


Solution

  • You need to use raw_input instead of input, because input runs eval on the input. (Only in python 2, in Python 3 input has the same behavior of raw_input and raw_input is removed)

    What that means is that after getting your input, python would evaluate your input as if it was code.
    Try entering "3+2*5-2" in the input and see the output.

    (Note that writing something like:"x = 5" won't work, because eval just evaluates an expression, like y+3 (assuming y is defined) and it does not actually run the code)

    (But really, you should use python 3 if you are just learning Python and you are not already used to python2)