Python input error

后端 未结 4 698
[愿得一人]
[愿得一人] 2021-01-14 12:10

I\'m running python 2.7.10 on Mac OSX 10.9.5m and it\'s not working. Here\'s the code:

# YourName.py
name = input(\"What is your name?\\n\")
print(\"Hi, \",          


        
4条回答
  •  无人共我
    2021-01-14 12:29

    For the version of Python you are using, you should be using raw_input instead of input.

    You can change this line of code:

    name = input("What is your name?\n")
    

    to this:

    name = raw_input("What is your name?\n")
    

    While you are using Python 2 it would be a good idea to only use raw_input. When you use input, Python will always try to "evaluate" the expression you are entering.

    Here is an explanation on why using input would not be a good for Python 2:

    So if you enter a 5, it will come back as the number 5 (int in Python).

    But if you enter bob, it thinks you are giving Python a "variable" called bob to evaluate, but bob is not defined as a variable in your program. This example actually gives the error you are getting:

    NameError: name 'bob' is not defined
    

    In Python if you enter a variable that does not exist, that is the error you get. Look at this example I made:

    I tried printing the variable d without assigning d anything:

    >>> d
    Traceback (most recent call last):
      File "", line 1, in 
    NameError: name 'd' is not defined
    

    So, if you want to give bob as a string to your input, input is expecting you to give bob quotes to make it a valid string like this: "bob". To avoid all this, raw_input is the right way to go.

    If you ever decide to use Python 3, Python 3 replaces raw_input with input. But it acts exactly like Python 2's raw_input.

    Good luck with your programming!


    Here is the documentation on raw_input:

    https://docs.python.org/2/library/functions.html#raw_input

提交回复
热议问题