问题:Python 3中的raw_input()和input()有什么区别?
raw_input()和input()Python 3有什么区别?
回答 0
区别在于raw_input()Python 3.x中不存在,而input()确实存在。实际上,raw_input()已将旧名称重命名为input(),而旧名称input()已消失,但是可以使用轻松地对其进行模拟eval(input())。(请记住这eval()是邪恶的。如果可能,请尝试使用更安全的方法来解析输入。)
回答 1
在Python 2中,raw_input()返回一个字符串,并input()尝试将输入作为Python表达式运行。
由于获取字符串几乎总是您想要的,因此Python 3做到了input()。正如Sven所说,如果您想要旧的行为,那就eval(input())可以了。
回答 2
Python 2:
- raw_input()完全接受用户键入的内容,并将其作为字符串传递回。
- input()首先采用- raw_input(),然后对其执行- eval()。
主要区别在于,input()期望语法正确的python语句raw_input()没有。
Python 3:
- raw_input()被重命名为,- input()因此现在- input()返回确切的字符串。
- 旧的input()被删除。
如果要使用旧的input()(意味着需要将用户输入评估为python语句),则必须使用手动进行操作eval(input())。
回答 3
在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尝试将rahda评估为变量而非字符串。为了避免这种情况,我们可以在输入中使用双引号,例如“ harsha”:
>>> 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函数评估用户输入。
回答 4
我想在每个人为python 2用户提供的解释中添加更多细节。raw_input(),到现在为止,您已经知道该功能可以评估用户以字符串形式输入的数据。这意味着python甚至不会尝试再次理解输入的数据。它只会考虑输入的数据将是字符串,无论它是实际的字符串还是int或其他任何值。
而input()在另一方面试图理解用户输入的数据。因此,像这样的输入helloworld甚至会将错误显示为’ helloworld is undefined‘。
总之,对于python 2来说,也要输入字符串,您需要像’ helloworld‘ 一样输入它,这是python中使用字符串的常用结构。
回答 5
如果您想确保自己的代码与python2和python3一起运行,请在脚本中使用function input()并将其添加到脚本的开头:
from sys import version_info
if version_info.major == 3:
    pass
elif version_info.major == 2:
    try:
        input = raw_input
    except NameError:
        pass
else:
    print ("Unknown python version - input function not safe")

