简体   繁体   English

如何在Python 2中从键盘获取用户输入?

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

I wrote a function in Python which prompts the user to give two numbers and adds them. 我在Python中编写了一个函数,它提示用户给出两个数字并添加它们。 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. 出于某种原因,当我在shell中运行它时,在进入城市后我得到“名称未定义”。

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

If you're on Python 2, you need to use raw_input : 如果您使用的是Python 2,则需要使用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 input会导致您键入的任何内容被评估为Python表达式,因此您最终会得到

a = whatever_you_typed

So if there isn't a variable named whatever_you_typed you'll get a NameError . 因此,如果没有名为whatever_you_typed的变量,您将获得NameError

With raw_input it just saves whatever you type in a string, so you end up with 使用raw_input它只会保存您在字符串中键入的内容,因此您最终会使用

a = 'whatever_you_typed'

which points a at that string, which is what you want. 它指向a在该字符串,这是你想要的。

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. 这是一个安全隐患,因为Python 3.x,input()的行为类似于raw_input(),它已被删除。

you want to use raw_input . 你想使用raw_input input is like eval input就像是eval

You want to use raw_input() instead. 您想要使用raw_input() input() expects Python, which then gets eval ed. input()需要Python,然后进行eval

You want raw_input , not input . 你想要raw_input ,而不是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. 在Python 2.x中, input请求Python表达式(如num1 + 2 ),然后对其进行求值。 You want raw_input which allows one to ask for arbitrary strings. 你想要raw_input ,它允许一个人要求任意字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM