Battery_Initial = raw_input("Enter Current Capacity:"))
if Battery_Initial < 0:
print 'Battery Reading Malfunction'
elif Battery_Initial > 80:
print 'Battery Reading Malfunction'
到目前为止,这是我的计划。我想知道是否有办法只允许输入,如0.5,1.0,1.5,基本上是0.5区间。
答案 0 :(得分:2)
您需要使用float()
而不是int()
,因为int()
期望十进制输入不是浮点数。
Battery_Initial = float(raw_input("Enter Current Capacity:"))
<强>输出:强>
$ python so27.py
Enter Current Capacity:0.5
$ python so27.py
Enter Current Capacity:81.1
Battery Reading Malfunction
$ python so27.py
Enter Current Capacity:-1.2
Battery Reading Malfunction
$ python so27.py
Enter Current Capacity:-1
Battery Reading Malfunction
使用类似的东西:
In [271]: [i/float(2) for i in range(1,10)]
Out[271]: [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
用法:
if Battery_Initial in (i/float(2) for i in range(1,10)):
#do something here
或@Joran Beasley的建议:
if Battery_Initial % 0.5 ==0:
#do something here