如何修复在Python中无法正常运行的while循环

时间:2019-10-16 20:54:59

标签: python while-loop

因此,我正在编写一个程序来计算用户输入的mpg,但是我的while循环无法正常工作。这是到目前为止我得到的:

#This program calculates miles per gallon the user enter
totalMPG = 0.0

#Ask user for the gallons used
gallons = input ('Enter gallons used(-1 to end): ')
#convert gallons to int
gallons = float(gallons)
#Ask user for the miles driven 
miles_driven = input("Enter the miles driven: ")
#convert miles to a float number
miles_driven = float(miles_driven)


# calculate miles/gallon and round 
mpg = miles_driven / gallons
mpg = round(mpg,2)

#print out mpg
print('Your miles per gallon is: ', mpg)


#while gallons does not equal -1
while gallons != "-1":

   mpg_value = float(mpg)
   totalMPG += mpg_value
   gallons = input("Enter gallons used (-1 to end): ")
   miles_driven = input("Enter the miles driven: ")
   print ('Your miles per gallon is: ', mpg)

print("Your total miles per gallons is: ", totalMPG)

avg = totalMPG / mpg
print ("You're average miles per gallons is ", avg)

当我输入-1退出程序时,它直接询问输入里程。

3 个答案:

答案 0 :(得分:2)

pip3 install 'grpcio==1.23.0' --force-reinstall

您转换后的输入为gallons = float(gallons) ... while gallons != "-1": ;您将其与字符串进行了比较。这些永远不可能相等。使用另一个。

在循环中,您将float保留为字符串。但是,您需要gallons才能循环返回以检查miles的值并退出循环。简而言之,您的循环退出逻辑是乱序的:您需要在循环的底部处输入gallons

答案 1 :(得分:1)

  

最好使用while Truebreak some_condition表达式。

调试:

print(type(gallons)) # output: int

所以gallons永远不会"-1"

代码:

# python3.x
# This program calculates miles per gallon the user enter

def calculate_mpg():
    _GET_GALLONS_MSG = "Enter gallons used (-1 to end): "
    _GET_MILES_DRIVEN_MSG = "Enter the miles driven: "
    _MPG_FINAL_MSG = "Your miles per gallon is: "
    _MPG_AVG_MSG = "You're average miles per gallons is "

    total_mpg, counter = 0.0, 0

    while True:

        try:
            gallons = float(input(_GET_GALLONS_MSG))

            if gallons == -1:
                break
            miles_driven = float(input(_GET_MILES_DRIVEN_MSG))

            total_mpg += round(gallons/miles_driven, 2)
            counter += 1

        except ValueError as e:
            print(e)

    avg_mpg = total_mpg / counter

    print(_MPG_FINAL_MSG, total_mpg)
    print(_MPG_AVG_MSG, avg_mpg)


if __name__ == '__main__':
    calculate_mpg()

答案 2 :(得分:0)

while gallons != "-1":并不意味着gallons变成"-1"时循环就会退出。仅在每次迭代开始时检查条件。

如果要在分配gallons之后执行检查,则需要手动处理:

while True:

   mpg_value = float(mpg)
   totalMPG += mpg_value
   gallons = input("Enter gallons used (-1 to end): ")

   if gallons == "-1":  # Tell it to break from the loop here
       break

   miles_driven = input("Enter the miles driven: ")
   print ('Your miles per gallon is: ', mpg)