python health.py
编译上述代码会报错,显示为:
Traceback (most recent call last):
File "health.py", line 12, in <module>
if weight/height/height<=25:
TypeError: unsupported operand type(s) for /: 'str' and 'str'
即是说,通过raw_input()读取的输入为'str‘字符串格式,无法用于算数运算。
修改代码后:
#Health.py
print 'so,input your name please'
name = raw_input()
print 'hello,',name
print 'tell me your height'
height = input()
print 'and your weight'
weight = input()
condition = 'normal'
result = weight
if weight/height/height<=25:
condition = 'good'
else:
condition = 'bad'
print 'your health condition is',condition
运行后顺利通过,即通过input()方法能够顺利读取数据为整型。
查看手册后得知:
input([prompt])
Equivalent to eval (raw_input(prompt))
即Input()在本质上和raw_input()是一样的,只不过对raw_input()接收的字符串进行了数值等价转换处理罢了。
number_test = input()
number_test1 = raw_input()
print number_test1,number_test
应用上述例子测试后可以发现,输出结果如下:
1+2
1+2
1+2 3
所以很显然的,input()方法可以直接将表达式求值并返回结果,而raw_input()只是将输入作为字符串保存。
不过在手册中有这样一句话:Consider using the raw_input() function for general input from users.
所以,没有特殊的必要还是使用raw_input()把。