[英]How to end a while loop using break in python?
i wrote here a loop which asks the user if he want to repeat a block of instructions.我在这里写了一个循环,询问用户是否要重复一段指令。 And wanted to give the user three tries to choose what he wants (Yes / No) if he doesn't the loop end.如果他没有结束循环,则想让用户尝试三次选择他想要的(是/否)。 This is my code:这是我的代码:
# Ask for repeating
i = 0
def question():
global i
while True:
print("Give another try?")
answer = input("(Y/N): ")
answer = answer.upper()
if answer == 'Y':
main()
elif answer == 'N':
print("Thank you for participating")
break # here it works when 'n' is typed
else: # i count how much the while loop id repeated
if (i < 2):
i += 1
question()
else: # else is executed when i == 2
print("don't Play with us!!")
break # here it doesn't work.
I want help.我需要帮助。
x = True
i = 0
def question():
# Ask for repeating
global i
global x
while x is True:
print("Give another try?")
answer ='a'
answer = answer.upper()
if answer == 'Y':
pass
elif answer == 'N':
print("Thank you for participating")
break # here it works when 'n' is typed
else: # i count how much the while loop id repeated
if (i < 2):
i += 1
question()
else: # else is executed when i == 2
print("don't Play with us!!")
x = False # here it doesn't work.
Add another break outside the last else block.在最后一个 else 块之外添加另一个中断。 Your code should be你的代码应该是
i = 0
def question():
global i
while True:
print("Give another try?")
answer = input("(Y/N): ")
answer = answer.upper()
if answer == 'Y':
main()
elif answer == 'N':
print("Thank you for participating")
break # here it works when 'n' is typed
else: # i count how much the while loop id repeated
if (i < 2):
i += 1
question()
else: # else is executed when i == 2
print("don't Play with us!!")
break # here it doesn't work.
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.