-1

I made a Hangman game in Python. Somehow, the break statement at the 6th line counting from the last line doesn't work completely. The if statements below the while loop are all broken, but the 3 lines under the while loop is still looping until the While loop completes. I have no idea how to solve this problem.

The input (partially) is as below:

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")
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

0

break only gets you out of the current loop, but not the one above. If you want to break out of everything, you could create a break-flag, that gets you out of the while-loop also:

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
py_coffee
  • 85
  • 10