Uday Patel
Uday Patel

Reputation: 31

Conditional Count Loop Python

I'm trying to find out where my mistake is in the following code which is about guessing a word.

If I type in the missing word, "ghost", it should end the game but it continues to ask for it.

Where is my mistake?

number = 0
missword = "ghost"
while number < 3:
    guess = input("What is the missing word? ")
    if guess != "ghost":
        print("Try again")
        number = number + 1
    elif guess == missword:
        print("Game Over")
    else:
        print("Game over")

Upvotes: 0

Views: 779

Answers (1)

NDevox
NDevox

Reputation: 4086

All your loop does is print, you need a break statement:

number=0
missword="ghost"
while number<3:
    guess = input("What is the missing word? ")
    if guess!="ghost": # Assuming you actually want this to be missword?
        print("Try again")
        number += 1 # Changed to a unary operator, slightly faster.
    elif guess==missword:
        print("Game Over")
        break
    else:
        print("Game over")
        # Is this ever useful?

break exits a loop before the exit condition has been satisfied. Print on the other hand simply outputs text to stdout, nothing else.

Upvotes: 6

Related Questions