Ask coding questions

← Back to all posts
How do I make the code stop after three guesses
niteeshtapre (0)

I don't understand how to stop the code completely after 3 guesses, it either give me an error message or continues?
BTW: its a random number generator.

Answered by UniqueOstrich18 (290) [earned 5 cycles]
View Answer
Commentshotnewtop
UniqueOstrich18 (290)

Here's the fixed code:

import random
guesses = 0

while guesses<3:
  value = random.randint(1, 10)
  number_1 = input("\nEnter your guess (1-10): ")
  if number_1.isdigit():
    number_1 = int(number_1)
    if number_1 == value:
      print("You guessed the number!\nThe number generated was "+str(value))
      break
    else:
      print("Wrong!\nThe number generated was "+str(value))
  else:
    print("Wrong!\nThe number generated was "+str(value))
  guesses += 1

If this was helpful, please mark it as the answer.

AlexanderTarn (274)

put the guesses variable outside of the loop, because every time you go through the loop guesses is reset to 0

CodingCactus (3089)

don't have a while True:
have something more like while guesses < 3:

niteeshtapre (0)

@CodingCactus I replaced that but now it says
Traceback (most recent call last):
File "main.py", line 3, in <module>
while guesses < 3:
NameError: name 'guesses' is not defined

CodingCactus (3089)

@niteeshtapre above the loop write guesses = 0
at the bottom (but still in the loop) write guesses += 1

niteeshtapre (0)

@CodingCactus It now says 'guesses' is not defined anything about that?
Also have I put it in the correct place