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

时光总嘲笑我的痴心妄想 提交于 2019-12-02 02:13:43

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.

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.

you want to use raw_input. input is like eval

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

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.

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.

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