Python Sentinel不工作

时间:2014-03-14 15:34:10

标签: python

我无法弄清楚为什么这个哨兵不起作用。我已经搜遍了所有的答案无济于事。谢谢你的帮助!

gas = 0
miles = 0
miles = int(input("Enter number of miles driven(enter -11 to exit): "))
while miles != -11:
    gas = int(input("Enter the number of gallons of gas used: "))
    print ("The number of miles entered was:", miles)
    print ("The number of gallons of gas used was:", gas)
    mpg = miles/gas
    print ("The MPG was:", mpg)

结果如下:

Enter number of miles driven(enter -11 to exit): 100
Enter the number of gallons of gas used: 10
The number of miles entered was: 100
The number of gallons of gas used was: 10
The MPG was: 10.0
Enter the number of gallons of gas used: -11
The number of miles entered was: 100
The number of gallons of gas used was: -11
The MPG was: -9.090909090909092
Enter the number of gallons of gas used:

2 个答案:

答案 0 :(得分:1)

您还应该包括周期中的里程数。

gas = 0
miles = 0
while miles != -11:
    miles = int(input("Enter number of miles driven(enter -11 to exit): "))
    gas = int(input("Enter the number of gallons of gas used: "))
    print ("The number of miles entered was:", miles)
    print ("The number of gallons of gas used was:", gas)
    mpg = miles/gas
    print ("The MPG was:", mpg)

即使在这种情况下,程序会在检查哨兵状况之前询问气体量,因此更好的版本是:

gas = 0
miles = 0
while True:
    miles = int(input("Enter number of miles driven(enter -11 to exit): "))
    if miles==-11:
        break
    gas = int(input("Enter the number of gallons of gas used: "))
    print ("The number of miles entered was:", miles)
    print ("The number of gallons of gas used was:", gas)
    mpg = miles/gas
    print ("The MPG was:", mpg)

答案 1 :(得分:1)

使用空白行代替“sentinel”...我也会使用iter的两个表单版本重写它:

for miles in iter(lambda: input('Enter miles (or enter to exit): '), ''):
    try:
        miles = int(miles)
        gas = int(input('Enter gas used: '))
        print('MPG was: ', miles/gas)
    except (ValueError, ZeroDivisionError): # int type conversion failed or div by 0
        print('You must enter valid numbers and gas used must be > 0 or press enter to exit')