python中input()和raw_input()的区别

时间:2022-08-15 20:25:52

使用input和raw_input都可以读取控制台的输入,input()只能接受int,float或由它们组成的表达式:

Python 2.7.5 (default, Mar 19 2014, 07:24:16)
[GCC 4.5.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> input("input something: ")
input something: 123
123
>>> input("input something: ")
input something: abc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'abc' is not defined
>>>

input和raw_input在处理数字时是有区别的:

1.输入为纯数字时
input返回的是数值类型,如int,float
raw_inpout返回的是字符串类型,string类型

print "how old are you?"
age1 = input()
print "%r" % age1
print
age2 = raw_input()
print "%r" % age2

返回结果:
how old are you?
22
22

22
'22' //raw_input()把输入整形当做字符串处理

2.输入字符串为表达式
input会计算在字符串中的数字表达式,而raw_input不会。

sum = input()
print "%r" % sum
print
sum = raw_input()
print "%r" % sum

结果:

1+2
3

1+2
'1+2'