How do I get user input from the keyboard in Python 2?

北战南征 提交于 2019-12-02 02:30:37

问题


I wrote a function in Python which prompts the user to give two numbers and adds them. It also prompts the user to enter a city and prints it. For some reason, when I run it in a shell, I get "name is not defined" after I enter the city.

def func_add(num1, num2):
   a = input("your city")
   print a
   return num1 + num2 

回答1:


If you're on Python 2, you need to use raw_input:

def func_add(num1, num2):

   a = raw_input("your city")
   print a
   return num1 + num2 

input causes whatever you type to be evaluated as a Python expression, so you end up with

a = whatever_you_typed

So if there isn't a variable named whatever_you_typed you'll get a NameError.

With raw_input it just saves whatever you type in a string, so you end up with

a = 'whatever_you_typed'

which points a at that string, which is what you want.




回答2:


input()

executes (actually, evaluates) the expression like it was a code snippet, looking for an object with the name you typed, you should use

raw_input()

This is a security hazard, and since Python 3.x, input() behaves like raw_input(), which has been removed.




回答3:


you want to use raw_input. input is like eval




回答4:


You want to use raw_input() instead. input() expects Python, which then gets evaled.




回答5:


You want raw_input, not input.

input(...)
    input([prompt]) -> value

    Equivalent to eval(raw_input(prompt)).

As opposed to...

raw_input(...)
    raw_input([prompt]) -> string

    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.



回答6:


In Python 2.x, input asks for a Python expression (like num1 + 2) which is then evaluated. You want raw_input which allows one to ask for arbitrary strings.



来源:https://stackoverflow.com/questions/7450223/how-do-i-get-user-input-from-the-keyboard-in-python-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!