2011-02-06 88 views
274

python3.x中raw_input()input()和有什么不一样?python3.x中raw_input()和input()之间的区别是什么?

+1

如何制作兼容Python 2和Python 3的输入程序? – 2016-05-04 12:08:31

+1

为此,您尝试将`input`设置为`raw_input`并忽略名称错误。 – 2016-05-04 14:38:52

+1

查看'six'库以获取Python 2和3的兼容性。 – 2017-11-02 21:37:05

回答

325

区别在于Python 3.x中不存在raw_input(),而input()则不存在。实际上,旧的raw_input()已重命名为input(),而旧的input()已不存在,但可以通过使用eval(input())轻松进行模拟。 (请记住,eval()是邪恶的,所以如果尝试使用解析您的输入可能的话最安全的方法。)

+55

“raw_input”...有什么区别?“ - “不同的是,没有`raw_input`。” ...相当大的差异,我会说! – 2015-02-10 21:03:05

170

在Python ,raw_input()返回一个字符串,并input()尝试运行输入作为Python表达式。

由于得到一个字符串几乎总是你想要的,所以Python 3用input()这样做。正如斯文所说,如果你想要老行为,eval(input())的作品。

94

的Python 2:

  • raw_input()将用户输入的到底是什么,并将其回为一个字符串。

  • input()先取raw_input(),然后再对其执行eval()

的主要区别在于input()预计语法正确的蟒蛇声明,其中raw_input()没有。

的Python 3:

  • raw_input()更名为input()所以现在input()返回精确的字符串。
  • 旧的input()已被删除。

如果你想使用旧input(),这意味着你需要评估用户输入作为一个python语句,你必须使用eval(input())做手工。

4

我想补充一点细节给大家提供的解释为python 2用户raw_input(),到目前为止,您知道该函数将用户输入的数据作为字符串进行评估。这意味着python不会尝试再次理解输入的数据。所有它会考虑的是输入的数据将是字符串,无论它是否是实际的字符串或int或任何东西。

另一方面input()试图了解用户输入的数据。所以像helloworld这样的输入甚至会将错误显示为'helloworld is undefined'。

总之,对于python 2,要输入一个字符串,您需要输入它,如'helloworld',这是python使用字符串时常用的结构。

20

在Python 3中,raw_input()不存在,这已经被Sven提及。

在Python 2中,input()函数会评估您的输入。

实施例:

name = input("what is your name ?") 
what is your name ?harsha 

Traceback (most recent call last): 
    File "<pyshell#0>", line 1, in <module> 
    name = input("what is your name ?") 
    File "<string>", line 1, in <module> 
NameError: name 'harsha' is not defined 

在上面的例如,Python 2.x的正试图评估戒作为变量而不是字符串。为了避免这种情况,我们可以使用双引号来我们的输入,如“戒”:

>>> name = input("what is your name?") 
what is your name?"harsha" 
>>> print(name) 
harsha 

的raw_input()

的raw_input的()`函数不评估,它只会读不管你输入。

实施例:

name = raw_input("what is your name ?") 
what is your name ?harsha 
>>> name 
'harsha' 

实施例:

name = eval(raw_input("what is your name?")) 
what is your name?harsha 

Traceback (most recent call last): 
    File "<pyshell#11>", line 1, in <module> 
    name = eval(raw_input("what is your name?")) 
    File "<string>", line 1, in <module> 
NameError: name 'harsha' is not defined 

在以上示例中,我只是想评估与eval功能的用户输入。

相关问题