Python input error

后端 未结 4 694
[愿得一人]
[愿得一人] 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:23

    Python 3.X Syntax for getting User Input

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

    Python 2.X Syntax for getting User Input

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

    0 讨论(0)
  • 2021-01-14 12:26

    use raw_input in python 2.7.1:

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

    Otherwise you have to rely on the user to know well-enough to input in quoted string. like "David", or the input attempts to evaluate a name (variable/object/etc) and if there is no such name in scope, you'll get the error.

    Alternatively, use exception handling:

    name = input("What is your name?\n")
    try:
        print("Hi, ", name)
    except NameError, e:
        print("Please enclose your input with quotes")
    
    0 讨论(0)
  • 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 "<stdin>", line 1, in <module>
    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

    0 讨论(0)
  • 2021-01-14 12:35

    Input tries to evaluate if the given string as a program. For a string alone use raw_input. Or you have to quote the string you had on input to allow python to interpret it as a string. For example:

    "Ella"
    
    0 讨论(0)
提交回复
热议问题