python3中rawinput_python3.x中的raw_input()和input()有什么区别?

python3.x中的raw_input()和input()有什么区别?

#1楼

Python 2:

raw_input()完全接受用户键入的内容,并将其作为字符串传递回。

input()首先使用raw_input() ,然后对其执行eval() 。

主要区别在于input()需要语法正确的python语句,而raw_input()则不需要。

Python 3:

raw_input()重命名为input()因此现在input()返回确切的字符串。

旧的input()已删除。

如果要使用旧的input() ,这意味着需要将用户输入评估为python语句,则必须使用eval(input())手动进行操作。

#2楼

我想在每个人为python 2用户提供的解释中添加更多细节。 raw_input() ,到目前为止,您已经知道该操作可以评估用户以字符串形式输入的数据。 这意味着python甚至不会尝试再次理解输入的数据。 它只会考虑输入的数据将是字符串,无论它是实际的字符串还是int或其他任何值。

另一方面, input()试图理解用户输入的数据。 因此,像helloworld这样的输入甚至会显示错误,因为“ helloworld is undefined ”。

总之,对于python 2来说 ,也要输入字符串,您需要像“ helloworld ”一样输入它,这是python中使用字符串的常用结构。

#3楼

在Python 3中,Sven已经提到过raw_input()不存在。

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

例:

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

what is your name ?harsha

Traceback (most recent call last):

File "", line 1, in

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

File "", line 1, in

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 "", line 1, in

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

File "", line 1, in

NameError: name 'harsha' is not defined

在上面的示例中,我只是尝试使用eval函数评估用户输入。

#4楼

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

#5楼

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

由于获取字符串几乎总是您想要的,因此Python 3使用input()做到了。 正如Sven所说,如果您想要旧的行为,则eval(input())可以工作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值