Python中的input()和raw_input()

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()把。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值