Practice Python Exercise 9

  • #### Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. (Hint: remember to use the user input lessons from the very first exercise)

Extras:

  • Keep the game going until the user types “exit”
  • Keep track of how many guesses the user has taken, and when the game ends, print this out.

In [ ]:
#Main method blueprint
import random
def main():
    random_num = random.randint(1,9)
    try:
        while True:
            
            user_input = int(input("Enter a number (1 to 9)"))
            dif = random_num - user_input
            
            if user_input in range(0,10):
                if dif > 0:
                    print("too low")
                    if wantToContinue() == "Y": continue 
                    else: break
                    
                    
                elif dif < 0:
                    print("too high")
                    if wantToContinue() == "Y": continue 
                    else: break
                    
                else:
                    print("Correct")
                    if wantToContinue() == "Y": continue 
                    else: break
                    
            
        
    except:
        print("game over")
def wantToContinue():
    return input("Do you wana continue ?:")
    
if __name__ == '__main__':
    main()