Python:使用字符串命令终止while循环

时间:2015-08-24 20:34:29

标签: python loops while-loop

我想添加允许用户使用字符串命令终止以下程序的选项(例如'退出'或退出' ),但由于用户输入只接受和处理整数,我看不到添加该字符串退出命令的方法。目前,我已经想出如何添加一个整数退出命令(" 00")。

(只要我问这个问题,我第一次在这个论坛上,技术问题:我如何复制和过去代码,使其看起来与我的Idle编译器屏幕上看起来完全一样?我想要缩进函数定义的主体。)

def balance_finder(amount):
if amount < 0:
    amount -= 10;

elif amount == 0:
    amount -= 5;

elif (amount > 0 and amount < 500):
    amount -= 1;

elif (amount > 500 and amount < 1000):
    amount += int(amount / 100);

else:
    amount += int(amount / 100) * 2;

print ("Your balance is: ", amount);

done = False;
while not done:
    amount = int(input("Please enter your balance (or type '00' to exit): "));
    if amount == 00:
        done = True;
        print ("Goodybye.");
    else:
        balance_finder(amount);

2 个答案:

答案 0 :(得分:1)

只需检查它是否为整数,并根据该行为进行操作:

while not done:
    amount = input("Please enter your balance (or type 'quit' to exit): ")
    try:
        amount = int(amount)
    except ValueError: # couldn't convert to integer
        done = True
        print("Goodbye.")
    else: # no error when converting to integer
        balance_finder(amount)

循环将以任何不是整数的输入结束,例如'''quit''3.9'

答案 1 :(得分:1)

在将输入转换为int之前,请检查&#39;退出&#39;或者&#39;退出&#39;。

the_input = input("Please enter your balance (or type 'exit' to exit): ")
if the_input == 'exit' or the_input == 'quit':
    done = True
    print ("Goodybye.")
else:
    amount = int(the_input)
    balance_finder(amount)