Python如果Else Loop

时间:2012-12-06 05:16:03

标签: python

我的代码就是这样:

Rate = input ("Enter Desired Rate of Charge: ") #User will be prompted to enter the charge rate of the system
if Rate < 0.5:
#If the charge rate entered is less than 0.5 kWhs
    print "Charge Rate Too Low: Please consider revision" #Tells the user the rate is too low
elif Rate > 2.0:
#Also, if the charge rate entered is greater than 2.0 kWhs...
    print "Charge Rate Too High: Please consider revision" #Tells the user the rate is too high
else:
#Otherwise, for any number entered between the bounds of 0.5 and 2.0 kWhs...
    print '\n' #Page break for new conditions.

如果输入的整数小于0.5或大于2,我需要它重新提示用户,当用户这样做时,然后将该整数保存为Rate并继续。谢谢。

2 个答案:

答案 0 :(得分:2)

我认为这比avasal的回答更清晰。此解决方案假定用户知道如何使用CTRL + C退出应用程序,否则您应该在用户输入Q或其他内容时添加对退出程序的支持。

rate = 0

while True:
    rate = input("Enter desired rate of charge: ")

    if not 0.5 < rate < 2:
        print "Rate must be between 0.5 and 2."
    else:
        break

答案 1 :(得分:0)

添加while循环,直到速率小于0.5或速率大于2.0

Rate = 0
while (Rate < 0.5) or (Rate > 2.0):
    Rate = input ("Enter Desired Rate of Charge: ") #User will be prompted to enter the charge rate of the system
    if Rate < 0.5:
    #If the charge rate entered is less than 0.5 kWhs
        print "Charge Rate Too Low: Please consider revision" #Tells the user the rate is too low
    elif Rate > 2.0:
    #Also, if the charge rate entered is greater than 2.0 kWhs...
        print "Charge Rate Too High: Please consider revision" #Tells the user the rate is too high
    else:
    #Otherwise, for any number entered between the bounds of 0.5 and 2.0 kWhs...
        print '\n' #Page break for new conditions.