Home > Software design >  How can I limit the number of user tries in this guessing game?
How can I limit the number of user tries in this guessing game?

Time:02-19

I'm completely new at this, I'm following a YouTube tutorial of a guessing game, however, after the game was finished, I wanted to limit the number of user tries to 3, using a while loop but I keep getting this error: I'm also aware I need to remove the while guess != random_number:

def guess(x):
    ^
IndentationError: expected an indented block after 'while' statement on line 537**

Guessing game:

 import random

 

     def guess(x):
         random_number = random.randint(1,x)
         guess = 0
         while guess != random_number:
             guess = int(input(f"Guess a number between 1 and {x}: "))
             if guess < random_number:
                 print("Too low, try again! ")
             elif guess > random_number:
                 print("Too high, try again")
    
         print(f"You got the number {random_number} correctly" )
      guess(50)

How exactly do I do this?

Please and thank you!

CodePudding user response:

Put something like num_guesses = 0 at the top of the function, then at the end of the while loop put in num_guesses = 1, then at the start of the loop put in something like if num_guesses < max_guesses: and have that print something and return. max_guesses can be a local or global variable, or you could make it another argument and pass it in.

CodePudding user response:

Your code will run without errors if you remove the extra indentations of the function definition and everything inside/after it. The whole block under "import random" has an extra indentation, and this is what is causing the error. "def guess" should be at the same indentation level as the import statement, as should your function call at the end of the program.

  • Related