0

I am learning Python and am working on a simple number guessing game. Basic premise is use is prompted to enter a number and then is told the guess is either too high, too low or correct. Once correct number is guessed, user is asked if they want to play again. However, when I type y the program exits back to prompt instead of re-starting. I've tinkered with the user prompts and the while and if portions and everything works EXCEPT for the part that is supposed to happen when user types y to play again.

This is the code I have:

import random

def playGame():
    number = random.randrange( 1, 11 )
    return number

chance = playGame()

print "\nI am thinking of a number between 1-10."
print "Can you guess my number?"
guess = int( raw_input( "Enter your guess. " ) )

while guess != chance:

    if guess > chance:
        print "Too high. Try again."
        guess = int( raw_input ("\nEnter your guess. " ) )


    if guess < chance:
        print "Too low. Try again."
        guess = int( raw_input ("\nEnter your guess. " ) )


    if guess == chance:
        print "Congratulations! You guessed my number!"

answer = raw_input( "\nWould you like to try again? (y or n) " )    
if answer == 'n':
    print "\nThank you for playing!"

if answer == 'y':
    playGame()

If I type n the string correctly prints out. But when I click y the program simply exits. I've searched online but everything I have found says I simply need to just type functionName() and it should cycle back to the function and repeat but it's not working for me. There's no maximum number of tries to guess the number. I have set it to keep guessing until correctly guessed.

What am I missing?

Thanks!

3
  • 1
    All that playGame function does is return a random number. Your program does exactly that when you enter y, and then stops, because, honestly, it does what you told it to. Commented Apr 10, 2016 at 17:18
  • 1
    If the user chooses y then you're calling the function that generates a random number, but you're not going back to the start of the code that asks them to guess Commented Apr 10, 2016 at 17:18
  • Hint: you need another while loop that contains the call to your random number generator and everything below it. You'll need to figure out how to break out of that loop. Commented Apr 10, 2016 at 17:31

2 Answers 2

3

You need to put the whole game into the playGame() function:

import random

def playGame():
    chance = random.randrange(1, 11)

    print "\nI am thinking of a number between 1-10."
    print "Can you guess my number?"
    guess = int( raw_input( "Enter your guess. " ) )

    while guess != chance:
        if guess > chance:
            print "Too high. Try again."
            guess = int( raw_input ("\nEnter your guess. " ) )

        if guess < chance:
            print "Too low. Try again."
            guess = int( raw_input ("\nEnter your guess. " ) )

    print "Congratulations! You guessed my number!"

playGame()

keep_playing = True
while keep_playing:
    answer = raw_input( "\nWould you like to try again? (y or n) " )    
    if answer == 'n':
        print "\nThank you for playing!"
        keep_playing = False

    if answer == 'y':
        playGame()

Otherwise you just reset the random number - the rest of the file isn't automatically run again, only the function body.

Sign up to request clarification or add additional context in comments.

3 Comments

FWIW, you can get rid of keep_playing . Instead, do while True and use break to break out of the loop.
Thank you! I see exactly what I did. I defined the function but didn't initially call for it to begin playing the game. I put the changes in and got the program to work. Thank you! It's great seeing where my mistake was and knowing how to fix it in the future.
You're very welcome. Glad to have helped. Please feel free to accept this (or any other) answer if it has fixed your problem.
-1

I think you might be misunderstanding how the return statement behaves in Python. playGame() simply returns a random number. After you hit the return statement in that function, your code returns back to where it was called from, which is the bottom of your script.

So, the flow kind of looks like this. We start here:

if answer == 'y':
    playGame() # we enter the playGame() function

Then go here:

def playGame():
    number = random.randrange( 1, 11 )
    return number # We get here, and return BACK to where we were called from

Now back to where we called from:

if answer == 'y':
    playGame()
    # The program continues...but nothing to execute here, so terminate

srowland's answer will only allow you to repeat once. A common pattern to these "repeat" problems is to wrap all of the code that needs to be repeated into a function call. Then, when the condition for repeating is met, just call that function. If you want to repeat indefinitely until the user enters 'n', then you probably want this:

import random

def playGame():
    number = random.randrange( 1, 11 )
    return number

def start_my_game():
    chance = playGame()

    print "\nI am thinking of a number between 1-10."
    print "Can you guess my number?"
    guess = int( raw_input( "Enter your guess. " ) )

    while guess != chance:

        if guess > chance:
            print "Too high. Try again."
            guess = int( raw_input ("\nEnter your guess. " ) )


        if guess < chance:
            print "Too low. Try again."
            guess = int( raw_input ("\nEnter your guess. " ) )


        if guess == chance:
            print "Congratulations! You guessed my number!"

    answer = raw_input( "\nWould you like to try again? (y or n) " )
    if answer == 'n':
        print "\nThank you for playing!"

    if answer == 'y':
        start_my_game() # Start the game again

# Start the game
start_my_game()

3 Comments

Nice answer, except it's much better to do the looping in the main game function with a while loop, rather than having the function calling itself recursively. In Python, recursion is not very efficient, and there is a recursion limit.
Good point, you shouldn't do this in production code, for reasons you've stated. I thought the recursive solution was simpler to understand, that's the only reason I put it up :).
Perhaps; some people find the whole concept of recursion hard to get their head around. And it's probably not good to give new programmers the idea that they should use recursion for stuff like this. Of course, recursion is invaluable for algorithms that are naturally defined recursively and hard to express iteratively, eg algorithms for processing recursive data structures like trees. But otherwise, it should be avoided in Python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.