如何在Python 2中从键盘获得用户输入? [英] How do I get user input from the keyboard in Python 2?

查看:312
本文介绍了如何在Python 2中从键盘获得用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Python编写了一个函数,提示用户输入两个数字并将其相加. 它还提示用户输入城市并进行打印.出于某种原因,当我在shell中运行它时,进入城市后会显示名称未定义".

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 

推荐答案

如果您使用的是Python 2,则需要使用raw_input:

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会使您键入的任何内容都被评估为Python表达式,所以最终得到

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

a = whatever_you_typed

因此,如果没有名为whatever_you_typed的变量,则会得到一个NameError.

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

使用raw_input可以保存您在字符串中键入的所有内容,因此最终得到

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

a = 'whatever_you_typed'

a指向该字符串,这就是您想要的.

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

这篇关于如何在Python 2中从键盘获得用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆