如何从用户输入循环回程序开始?
我刚开始学习使用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.')
我该如何添加一个循环,让程序在特定输入时重新开始呢?谢谢!
-Pottsy1 个回答
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
的变量,然后当你问是否要重新开始时,如果答案不是完全的“是”(无论是什么情况),那么就停止你的程序。