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

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