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

guessing program not able to guess the correct number

Hello, fellow Pyhtonistas,

I was able to code the logic of the program initially but a tad dazed on how I messed up the correct output. Whenever I provide a number input and page thru all of the available number guesses (from 0 to 9) it won't return that I have guessed it correctly until I page thru the numbers (from 0 to 9) again!. Also, in the restart function when I opt to play "no" it doesn't exit the game and continues even when I've included the else statement. Could you help me spot the errors I've made?

import random
# create an empty list to for the random numbers

def start_game():

    container = []
    for i in range(10):
        container.append(i)
    # randomly pick a number
    answer = random.choice(container)

    attempt = 1
    guess = input("Pick a number:> ")

    while guess != answer:
        guess
        attempt += 1

        try:

            guess = int(guess)

        except ValueError:

            print("{} is an invalid input please enter a number.".format(guess))

            start_game()

        else:

            if guess == answer:
                print("Got it you made {} attempt/s to guess the correct number!".format(attempt))
                # when user guesses correctly exit the program
                restart()

            elif guess > answer:
                print("It's lower!")

            elif guess < answer:
                print("It's higher!")

            start_game()


# Prompt the user to play again
def restart():

    play = input("You won the game do you want to play again!? (Yes/No): ")

    while play.lower() != "no":
        try:
            play = play
            start_game()

        except ValueError:
            print("{} that's an invalid input please enter a (Yes or No only).".format(play))
            restart()

        else:
            print("Thank you for playing the Number guessing game!, See you again!")

5 Answers

I would initialize as follows:

attempt = 0

because you haven't guessed yet

guess = -1

because it is outside the range of 0-9 and instead of the prompt

Otherwise your reporting is off. For example here I guessed 1 but

Pick a number:> 1                                                                                              
Pick a number:> 2                                                                                              
It's lower!                                                                                                    
Pick a number:> 1                                                                                              
Got it you made 3 attempt/s to guess the correct number!  

I got it on the first attempt.

You can also eliminate the continue statements since you are in a loop it will continue anyways

Delete guess after try as well

try:
    guess

KRIS NIKOLAISEN that made good sense!

would initialize as follows:

attempt = 0

because you haven't guessed yet

guess = -1

as it corrected the reporting on the total number of tries accumulated before guessing the correct number. Thank you for your help I removed also all the coninue and break statements as it slipped that I'm controling the flow thru the while loops, my bad and lessons learned.

Steven Parker
Steven Parker
243,095 Points

Your main loop in "start_game" contains additional calls to "start_game". So essentially, every guess is a completely new game. This means the "clues" you get after a guess are actually no help for the next guess. The loop should include the input, but not any calls to main function.

And the game never ends because when you say "no", the "restart" function just returns to the previous game (the one which called the new game you just finished).

When a function calls itself, that's called "recursion". It can be a useful technique for some situations, but it's not really suited for a simple repeating task like this.

Try re-writing the logic without having either function call itself and see if that resolves your issues.

@Steven Parker, I've attempted to utilise continue and break function into the code, however, I've included another input statement after the first while loop which I think is overkill if I omit this it transitions into an infinite loop. Also, when I opt not to play the game again it doesn't break out of the loop, might have misunderstood the use of continue and break for nested loops, I'm not really sure about it. Could you help me figure out this beautiful mess? :)

Code

import random

def start_game():

    container = []
    for i in range(10):
        container.append(i)
    # randomly pick a number
    answer = random.choice(container)

    attempt = 1
    guess = input("Pick a number:> ")

    while guess != answer:
        guess = input("Pick a number:> ")
        attempt += 1

        try:
            guess
            guess = int(guess)

        except ValueError:
            print("{} is an invalid input please enter a number.".format(guess))
            continue

        if guess == answer:
            print("Got it you made {} attempt/s to guess the correct number!".format(attempt))
            break

        elif guess > answer:
            print("It's lower!")
            continue

        elif guess < answer:
            print("It's higher!")
            continue

    play = input("You won the game do you want to play again!? (Yes/No): ")

    while play.lower() != "no":
        try:
            start_game()

        except ValueError:
            print("{} that's an invalid input please enter a (Yes or No only).".format(play))
            continue

        else:
            break

    print("Thank you for playing the Number guessing game!, See you again!")

REPL

>>> start_game()
Pick a number:> 3
Pick a number:> 3
It's higher!
Pick a number:> 4
It's higher!
Pick a number:> 55
It's lower!
Pick a number:> 4

It's higher!
Pick a number:> 3
It's higher!
Pick a number:> 4
It's higher!
Pick a number:> 5
It's higher!
Pick a number:> 6
It's higher!
Pick a number:> 7
Got it you made 10 attempt/s to guess the correct number!
You won the game do you want to play again!? (Yes/No): yes
Pick a number:> 3
Pick a number:> 3
It's higher!
Pick a number:> 4
It's higher!
Pick a number:> 5
Got it you made 4 attempt/s to guess the correct number!
You won the game do you want to play again!? (Yes/No): again!
Pick a number:>
Steven Parker
Steven Parker
243,095 Points

The first input is not used, so you can eliminate it:

    attempt = 0
    guess = None    # no "input" needed here

    while guess != answer:

And you don't need the "continues" or the "break", since the loop will continue by default anytime the guess is not equal to the answer, and stop when it is.

@Steven Parker, I'm quite happy that I've finally ran the program with insurance coverage of catching those exceptions too. I've synergised KRIS NIKOLAISEN and your advise to rethink the control flow of the program, could you kindly check my code found in the workspace with filename guess-test.py? I'm not sure if I'm still missing out something.

thank you in advance!

Steven Parker
Steven Parker
243,095 Points

Live workspace URL's are only temporary. To get a persistent one, use the snapshot function (the camera icon).

Oh yeah, here it is: https://w.trhou.se/zl0h9xh0ln

Steven Parker
Steven Parker
243,095 Points

I wasn't able to try the workspace because the "pyfiglet" module was not present.

But just looking it over, it seems like it would work better now. There's still a few curious things in there, though. For example:

    container = []
    for i in range(10):
        container.append(i)
    answer = random.choice(container)
# that seems rather complicated, you could just do this instead:
    answer = random.choice(range(10))
# but this would be more conventional:
    answer = random.randint(0, 9)

And another:

            if guess > max(range(10)):
# "max(range(10))" is always 9, so why not just:
            if guess > 9:

But congratulations on getting it working. :+1:

Yeah, this looks more efficient rather than creating a list thru a loop, it can be done in one line, never thought of it until now.

that seems rather complicated, you could just do this instead:

answer = random.choice(range(10))

Also, this code is simpler instead of calling those functions is better to hard assign it, thanks for the knowledge.

"max(range(10))" is always 9, so why not just:

       if guess > 9:

I think the wisdom derived from this project is heavier as it sticks to my brain's axon, anyways I will try to shoot for the "exceeds grade".

Appreciate your help Steven and Kris!

Happy Pythoning!