[英]How to break a loop depending on answer from input, then move on with the rest of the program
[英]How to break from loop to stop program from running
我正在尝试实施一个程序,在该程序中,我想根据以下标准进行检查,即一旦达到桌子或椅子的数量限制,循环应该中断并打印最终的打印语句。 从逻辑上讲,在第一个 break 语句之后,它会从第一个 for 循环中断,但不会中断完整的 for 循环并打印最终语句并继续迭代。
我希望达到最大数量的桌子或椅子,循环应该中断。
知道如何修改吗? 如果可以,我可以实现 while 语句 - 如何实现?
我是 python 的新手,发现这些练习很有趣,你的帮助会很大。
#variables
number_of_tables = 200
no_of_chairs = 500
for tables in range(0, number_of_tables):
for chairs in range(0, no_of_chairs):
prompt = "Bienvenue a la'restaurant"
answer = input("Please enter for how many people you need a table: ")
print(f"Welcome family of {answer}, please wait while we take you to your seat")
number_of_tables -= 1
no_of_chairs -= int(answer)
if number_of_tables == 0 or no_of_chairs == 0:
reply = "Good things need patience. We are full. Please wait in the lobby till a table gets empty. We thank you for understanding"
print(reply)
break;
print("Thank you for visiting us.")
您可以添加另一个变量来跟踪内部循环中断的事实:
number_of_tables = 200
no_of_chairs = 500
broken = False # this one
for tables in range(0, number_of_tables):
if broken:
break # out of the outer loop
for chairs in range(0, no_of_chairs):
prompt = "Bienvenue a la'restaurant"
answer = input("Please enter for how many people you need a table: ")
print(f"Welcome family of {answer}, please wait while we take you to your seat")
number_of_tables -= 1
no_of_chairs -= int(answer)
if number_of_tables == 0 or no_of_chairs == 0:
reply = "Good things need patience. We are full. Please wait in the lobby till a table gets empty. We thank you for understanding"
print(reply)
broken = True # signal to the outer loop
break;
也许最简单的就是将它包装在一个函数中:
def waiting(number_of_tables, no_of_chairs):
for tables in range(0, number_of_tables):
for chairs in range(0, no_of_chairs):
prompt = "Bienvenue a la'restaurant"
answer = input("Please enter for how many people you need a table: ")
print(f"Welcome family of {answer}, please wait while we take you to your seat")
number_of_tables -= 1
no_of_chairs -= int(answer)
if number_of_tables == 0 or no_of_chairs == 0:
reply = "Good things need patience. We are full. Please wait in the lobby till a table gets empty. We thank you for understanding"
print(reply)
return
waiting(200,500)
print("Thank you for visiting us.")
我会这样做:
#variables
number_of_tables = 200
no_of_chairs = 500
while number_of_tables != 0 and no_of_chairs != 0:
prompt = "Bienvenue a la'restaurant"
answer = input("Please enter for how many people you need a table: ")
print(f"Welcome family of {answer}, please wait while we take you to your seat")
number_of_tables -= 1
no_of_chairs -= int(answer)
reply = "Good things need patience. We are full. Please wait in the lobby till a table gets empty. We thank you for understanding"
print(reply)
print("Thank you for visiting us.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.