python 中的input()和raw_input()功能与使用区别

本文详细解析了Python中input()与raw_input()函数的区别,包括它们如何处理不同类型的输入数据,以及使用这些函数时应注意的事项。
在python中raw_input()和input()都是提示并获取用户输入的函数,然后将用户的输入数据存入变量中。但二者在处理返回数据类型上有差别。
input()函数是raw_intput()和eval()函数的功能的组合即:input()=eval(raw_input()),eval对用户输入的数据进行了求值,并返回求值结果。
raw_input()函数输入任何类型的数据都会被存储为一个字符串。
str类型-->str:
1 >>> s=raw_input("raw here:")
2 raw here:Tom ok!
3 >>> type(s)
4 <type 'str'>
5 >>> print s
6 Tom ok!
int类型-->str:
1 >>> s=raw_input("raw here:")
2 raw here:66
3 >>> type(s)
4 <type 'str'>
list类型-->str:
1 >>> s=raw_input("raw here:")
2 raw here:[1,2,3]
3 >>> type(s)
4 <type 'str'>
input()函数不改变输入数据的类型。
str类型-->str
1 >>> s=input("input here:")
2 input here:"Tom ok!"
3 >>> type(s)
4 <type 'str'>
5 >>> print s
6 Tom ok!
int类型-->int:
1 >>> s=input("input here:")
2 input here:55
3 >>> type(s)
4 <type 'int'>
list类型-->list:
1 >>> s=input("input here:")
2 input here:[1,2,3]
3 >>> type(s)
4 <type 'list'>
raw_input()函数输入任何类型的数据都会被视为一个字符串,且在输入字符串时不需要加引号。
1 >> s=raw_input("input your name:")
2 input your name:bell
3 >>> print s
4 bell
input()函数直接接受且不改变输入数据的类型,但是需要注意的是使用input()在输入字符串时需要添加引号,否则会报错。
 
不添加引号报错:
1 >>> s=input("input here:")
2 input here:hello
3 Traceback (most recent call last):
4   File "<stdin>", line 1, in <module>
5   File "<string>", line 1, in <module>
6 NameError: name 'hello' is not defined
添加引号正常:
1 >>> s=input("input here:")
2 input here:"hello"
3 >>>

 

 

转载于:https://www.cnblogs.com/luckygwt/p/6558249.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值