如何在python中使用break结束while循环?
我在这里写了一个循环,询问用户是否要重复一段指令。 并希望给用户三次尝试,以选择他想要的(是/否),如果他没有结束循环。 这是我的代码:如何在python中使用break结束while循环?,python,if-statement,while-loop,global-variables,break,Python,If Statement,While Loop,Global Variables,Break,我在这里写了一个循环,询问用户是否要重复一段指令。 并希望给用户三次尝试,以选择他想要的(是/否),如果他没有结束循环。 这是我的代码: # Ask for repeating i = 0 def question(): global i while True: print("Give another try?") answer = input("(Y/N): ") answer = answ
# 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=0
定义问题():
全球i
尽管如此:
打印(“再试一次?”)
回答=输入(“(是/否):”)
答案=答案。上限()
如果答案==“Y”:
main()
elif answer==“N”:
打印(“感谢您的参与”)
break#在这里输入“n”时有效
else:#我计算while循环id重复了多少次
如果(i<2):
i+=1
问题()
else:#当i==2时执行else
打印(“不要和我们玩!!”)
坏了,这里坏了。
我需要帮助。x=True
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.
i=0
定义问题():
#要求重复
全球i
全球x
虽然x是真的:
打印(“再试一次?”)
回答‘a’
答案=答案。上限()
如果答案==“Y”:
通过
elif answer==“N”:
打印(“感谢您的参与”)
break#在这里输入“n”时有效
else:#我计算while循环id重复了多少次
如果(i<2):
i+=1
问题()
else:#当i==2时执行else
打印(“不要和我们玩!!”)
x=False#这里不起作用。
在最后一个else块之外添加另一个中断。你的代码应该是
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
i=0
定义问题():
全球i
尽管如此:
打印(“再试一次?”)
回答=输入(“(是/否):”)
答案=答案。上限()
如果答案==“Y”:
main()
elif answer==“N”:
打印(“感谢您的参与”)
break#在这里输入“n”时有效
else:#我计算while循环id重复了多少次
如果(i<2):
i+=1
问题()
else:#当i==2时执行else
打印(“不要和我们玩!!”)
坏了,这里坏了。
打破
ohh这是我的错:break应该在第二个“else”之外。