如何从用户输入将程序循环回到开头?

时间:2014-05-05 14:35:41

标签: python loops restart

我刚刚开始使用python。我制作的第一个程序是小费计算器,我已经制作了三个版本来重写并添加更多。我要编写的代码的下一部分是一个提示是或否的问题的循环。当'是'时,我希望程序循环回到最开始,当'否'时,我希望程序退出,当有无效命令时,我希望程序打印('无效命令'。)并继续等待'是'或'否'。这是代码:

    print('Good evening sir, I am Tippos! Please, tell me the price of your meal and how much you would like to tip and I\'ll do the math for you!')
bill_amt = input('First sir, what was the price of your meal?(Please do not use signs such as "$"):')

tax = 1.13
x = float(bill_amt)
tip_amt = input('And how much would you like to tip? 10, 15, or maybe 20% Go on, any number sir!(Please do not use signs such as "%"):')
y = float(tip_amt)

tip_amt = x * (y / 100)
print('Your tip will cost you an extra' ,tip_amt, 'dollars.')
total_amt = (x + y) * tax
print('Your total cost will be' ,total_amt, 'dollars, sir.')

如何添加一个循环,在某个输入处重启程序? 谢谢! -Pottsy

1 个答案:

答案 0 :(得分:1)

一个好方法就是如下:

done = False
while not done:
    print('Good evening sir, I am Tippos! Please, tell me the price of your meal and how much you would like to tip and I\'ll do the math for you!')
    bill_amt = input('First sir, what was the price of your meal?(Please do not use signs such as "$"):')

    tax = 1.13
    x = float(bill_amt)
    tip_amt = input('And how much would you like to tip? 10, 15, or maybe 20% Go on, any number sir!(Please do not use signs such as "%"):')
    y = float(tip_amt)

    tip_amt = x * (y / 100)
    print('Your tip will cost you an extra' ,tip_amt, 'dollars.')
    total_amt = (x + y) * tax
    print('Your total cost will be' ,total_amt, 'dollars, sir.')
    if 'yes' != input('Do you want to start over?').lower():
        done = True

其中变量done在while循环中设置,然后当您提出问题重新开始时,如果答案不完全是肯定的(无论如何),那么您将停止算法。