我想知道是否有人可以帮助我弄清楚如何完全摆脱我的while循环并继续我的程序的其余部分。谢谢!
import time
while True:
company_name = input("\nWhat is the name of your company? ")
if company_name == "":
time.sleep(1)
print("\nThis is not eligible. Please try again")
else:
while True:
verify_name = input("\nPlease verify that {} is the correct name of your company \nusing Yes or No: ".format(company_name))
if verify_name.lower() == "no":
print("\nPlease re-enter your company name.")
time.sleep(1)
break
elif verify_name.lower() not in ('yes', 'y'):
print("\nThis is an invalid response, please try again.")
time.sleep(1)
break
else:
print("\nWelcome {}.".format(company_name))
verify_name == True
break
else:
break
#Continue with rest of my program
答案 0 :(得分:-1)
下面的解决方案添加了一个标志来控制何时突破设置为突破每个循环的外部循环,并在内部循环中没有发生中断时返回,即else
语句具有在内循环上达成了。
import time
no_break_flag = True
while no_break_flag:
no_break_flag = False
company_name = input("\nWhat is the name of your company? ")
if company_name == "":
time.sleep(1)
print("\nThis is not eligible. Please try again")
else:
while True:
verify_name = input("\nPlease verify that {} is the correct name of your company \nusing Yes or No: ".format(company_name))
if verify_name.lower() == "no":
print("\nPlease re-enter your company name.")
time.sleep(1)
break
elif verify_name.lower() not in ('yes', 'y'):
print("\nThis is an invalid response, please try again.")
time.sleep(1)
break
else:
print("\nWelcome {}.".format(company_name))
verify_name == True
break
else:
no_break_flag = True
#Continue with rest of my program
显然,当你在内循环上有条件while True
时,你总会通过中断退出,但是如果你有其他条件,那么只有在达到break
语句时才会破坏外部循环在内循环上。