Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Number Game Refinement Queston

Hello,

I have in issue with validating user input: if non integer is inserted, program crashes: looks like input_validation() doesn't work. First part of this function is working, since we are calling it from main_body() function and even passing a message as a string. Why "except" part doesn't work?

Additionally, once game is over (either user guessed the number or lost) - how to let the user start the game again?

Thanks :)

def number_generator():
    import random

    # generate a random number between 1 and 10
    random_num = random.randint(1, 10)
    print("......")
    print("Random number has been generated.")
    print("......")
    return random_num


#validating if number is an integer
def input_validation(message):
    while True:
        try:
            player_input = int(input(message))
        except ValueError:
            print("That's not a number, please try again")
            continue
        else:
            return player_input
            break

def main_body():
    #introduction
    number_of_tries = 6
    print("Hello, this is a Random Number Guessing Game. You will have {} tries to guess a random number in range from 1 to 10.".format(number_of_tries))
    random_num = number_generator()
    while number_of_tries > 0:
        # getting a number guess from the player
        # making sure it's an integer
            player_input = input_validation("Guess a number between 1 and 10: ")

            # compare guess to secret number
            if player_input == random_num:
                print("You selected {} and computer also selected {} - Congrats!".format(player_input, random_num))
                break
            elif player_input > random_num:
                number_of_tries = number_of_tries - 1
                print("Aim lower, but remember that you have {} tries left.".format(number_of_tries))
            elif player_input < random_num:
                number_of_tries = number_of_tries - 1
                print("Aim higher, but remember that you have {} tries left.".format(number_of_tries))
            else:
                number_of_tries = number_of_tries - 1
                print("Wrong! You now have {} tries left.".format(number_of_tries))
    else:
        print("You've lost! No tries left. ")

main_body()

    # catch if someone catches a non-integer
    # let people play again

1 Answer

What you have here seems to work for me. If I type 'asdf' the exception says "That's not a number, please try again." as it should.

To allow the user to play again, I would create a function that is called where ever the game is currently ended now. The function would look something like this:

def play_again():
    while True:
        player_input = input("Would you like to play again? Y / n ")
        if player_input.lower() not in 'yn':
            continue
        elif player_input.lower() == 'y':
            main_body()
        else:
            break

When the player types 'y' the function will call main_body() again and the game will start over; otherwise, the game is ended by breaking the while loop and not having anything else to run.

I would place a call to the 'play_again()' function in two places. I would replace the 'break' in the if statement if the player guesses correctly and I would call it just below the 'print()' in the final 'else:' statement when the player loses.

Let me know if this helps or if you need further clarification.