Thrillidas
Thrillidas

Reputation: 79

How to restart a loop if the input is wrong?

I'm new in python. I'm trying to code a basic hangman game, the thing is, when I put on purpuse a wrong answer, my for loop keep making the iteration as if nothing happen, I'd like that each time I mistake, the loop "freeze" o keep in the same letter until I put the correct answer.

This is my code:

word = input("Introduce a word ")

n = len(word)
print("The word has "+ str(n) + " letters")
print("Hint: The first letter is " + word[0])
print("")

for i in word:
    print(i)
    if i == input("Guess the letter: "):
        print("Correct")
    else:
        print("Wrong !")

Upvotes: 1

Views: 1948

Answers (1)

Matthias
Matthias

Reputation: 13222

Loop forever and break from the loop if the answer is correct.

for character in word:
    print(character)
    while True:
        if character == input("Guess the letter: "):
            print("Correct")
            break
        else:
            print("Wrong !")

The while part of the code in real world language: "I'm going to ask you forever until you give me the correct answer."

Upvotes: 2

Related Questions