Search code examples
pythoninfinite-loopindentationpython-3.10

Python - Guessing a number game: no output


What am I doing wrong here? I am trying to build a guessing a number game but not sure why the console doesn't display anything?!

import random

    game_random_number = random.randint(1, 100)
    game_active = True  
    
    
    while game_active:  
      game_start_message = "guess a number between 1 and 100"
      user_guess = int(input()) 
    if user_guess == game_random_number:
      print("You guessed it correctly")
      game_active = False
    elif user_guess < game_random_number:
      print("Too low guess again")
    else:
      print("Too high, guess again")

Solution

  • It works fine with the correct indentation. You otherwise fall in an infinite loop where you do nothing but request user to input a number.

    import random
    
    game_random_number = 42 # just for the test
    game_active = True  
        
        
    while game_active:  
        game_start_message = "guess a number between 1 and 100"
        user_guess = int(input()) 
        if user_guess == game_random_number:
            print("You guessed it correctly")
            game_active = False
        elif user_guess < game_random_number:
            print("Too low guess again")
        else:
            print("Too high, guess again")
    

    example:

    1
    Too low guess again
    2
    Too low guess again
    50
    Too high, guess again
    42
    You guessed it correctly
    

    NB. game_start_message = "guess a number between 1 and 100" doesn't do anything. Maybe you should rather print this string before the loop?