我的 break 语句没有中断 while 循环



我用Python制作了一个Hangman游戏。不知怎的,从最后一行算起的第6行的break语句并没有完全起作用。while循环下面的if语句都断开了,但while循环下的3行仍在循环,直到while循环完成。我不知道如何解决这个问题。

输入(部分(如下:

while attempt<chances:
input_answer=input("please input one alphabet you think it is correct= ")
attempt+=1
remaining_chances=chances-attempt
if input_answer in listed_question and blank_space in listed_question_bar:
print(f"you have {remaining_chances} chance{plural} left")
for ans in range(len(listed_question)):
if listed_question[ans]==input_answer:
listed_question_bar.pop(ans)
listed_question_bar.insert(ans,input_answer)
print(listed_question_bar)
if "_" not in listed_question_bar:
print("you win, game over")
break
elif input_answer not in listed_question:
print("you guessed incorrectly, try again")
print(f"you have {remaining_chances} chance{plural} left")
else:
print("game over, no more attempt left")

break只会让您退出当前循环,但不会退出上面的循环。如果你想突破一切,你可以创建一个突破标志,让你摆脱while循环:

while some_condition:
break_flag = False # init break_flag
for i in some_range:
if break_condition:
# set break_flag to True before breaking out of for-loop
break_flag = True 
break
# use break_flag to break out of while-loop
if break_flag:
break

最新更新