0
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 的间隔上。

4

1 回答 1

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
于 2012-11-26T21:47:51.280 回答