pythonpython-2.7python-3.xioterminal

'input' works in 3.5 IDLE but not in the terminal


Here is some basic code I've made:

userInput = input("Type in a random word:\n")
print("Here are the letters in that word")
for letters in userInput:
    print(letters)

Completely works in the 3.5 shell/IDLE but wont work in my terminal... Here is the error when i put the input as "test":

NameError: name 'test' is not defined

Any help?


Solution

  • In the terminal you are really running Python 2. raw_input() in Python 2 is the equivalent to input() in Python 3. input() in Python 2 will evaluate the input as a Python statement, so it tries to evaluate test as a variable name.

    If you are using Windows you can use the Python Launcher (py.exe) to specify the version of Python to run if you have multiple versions installed. It should already be in the path if you've installed Python 3. In Linux python3 should work.

    Example:

    C:\>py -3
    Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> input()
    test
    'test'
    >>> ^Z
    
    C:\>py -2
    Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> input()
    test
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<string>", line 1, in <module>
    NameError: name 'test' is not defined