Reputation: 11
trying to make a game where if you reach a certain number of guesses the while loop breaks
secret_word = "giraffe"
guess = ""
guess_count = 0
while guess != secret_word:
guess = input("enter guess: ")
guess_count += 1
print(guess_count)
if guess == secret_word:
print("You win")
else guess_count == "4":
print("You lost!")
break
Upvotes: 1
Views: 45
Reputation: 46
I kind of reformated the code, having else with a condition didn't really make sense so I switched it to:
secret_word = "giraffe"
guess = ""
guess_count = 0
limit = 4
while guess_count < limit:
guess = input("enter guess: ")
guess_count += 1
print(guess_count)
if guess == secret_word:
print("Congrats, You Win!!")
quit()
print('Sorry, too many guesses, you lose! :(')
Good luck with the game!!
Upvotes: 1
Reputation: 1223
Your code is almost there, you just need to make a few changes. First, you need a break statement within your win condition so the loop stops. Second, you need to change else
to elif
, or simply just an if
. Also, you need to compare guess_count
to an int
, not a str
.
Code:
secret_word = "giraffe"
guess = ""
guess_count = 0
while guess != secret_word:
guess = input("enter guess: ")
guess_count += 1
print(guess_count)
if guess == secret_word:
print("You win")
break
elif guess_count == 4:
print("You lost!")
break
Output:
enter guess:
dog
1
enter guess:
dog
2
enter guess:
dog
3
enter guess:
dog
4
You lost!
Upvotes: 2