使用input和raw_input都可以读取控制台的输入,input()只能接受int,float或由它们组成的表达式:
1 Python 2.7.5 (default, Mar 19 2014, 07:24:16) 2 [GCC 4.5.4] on linux2 3 Type "help", "copyright", "credits" or "license" for more information. 4 >>> input("input something: ") 5 input something: 123 6 123 7 >>> input("input something: ") 8 input something: abc 9 Traceback (most recent call last): 10 File "<stdin>", line 1, in <module> 11 File "<string>", line 1, in <module> 12 NameError: name ‘abc‘ is not defined 13 >>>
input和raw_input在处理数字时是有区别的:
1.输入为纯数字时
input返回的是数值类型,如int,float
raw_inpout返回的是字符串类型,string类型
1 print "how old are you?" 2 age1 = input() 3 print "%r" % age1 4 print 5 age2 = raw_input() 6 print "%r" % age2
返回结果:
1 how old are you? 2 22 3 22 4 5 22 6 ‘22‘ //raw_input()把输入整形当做字符串处理
2.输入字符串为表达式
input会计算在字符串中的数字表达式,而raw_input不会。
1 sum = input() 2 print "%r" % sum 3 print 4 sum = raw_input() 5 print "%r" % sum
结果:
1+2 3 1+2 ‘1+2‘
时间: 2024-10-11 00:22:32