mercredi 11 novembre 2020

Number guessing game with optional quit command

I'm trying to make a guessing game with the option for the user to quit the program, but I'm unable to get the 'quit' part of the program to work as intended.

from random import randint

userGuess = input("Pick a number from 1 to 1000: ")
guess = randint(1, 1000)
while userGuess != guess: 
    try: 
        userGuess = int(userGuess)
        if userGuess > guess: 
            print("The number you entered is higer than the guess. Try again.\n")
            userGuess = int(input("Pick a number from 1 to 1000: "))
        elif userGuess < guess: 
            print("The number you entered is lower than the guess. Try again.\n")
            userGuess = int(input("Pick a number from 1 to 1000: "))
        else:  
            print("You guessed it!")
            break
    except (TypeError, ValueError): 
        userGuess = str(userGuess)
        if userGuess.lower() == 'quit': 
            print("Quitting....")
            break

Whenever I run this program, if I type 'quit' when the game begins, it quits the program. However, if I guess a number before I type quit, the program goes through the if statements like it should, but when you try to quit after it just defaults, "the number entered is too low. try again" instead of quitting the program as intended.

I didn't know if there was a better way to handle the 'quit' command other than the try-except method.




Aucun commentaire:

Enregistrer un commentaire