Python Python Basics (2015) Number Game App Number Game Refinement

Richard Hummel
PRO
Richard Hummel
Pro Student 5,677 Points

After pressing 'n' game runs again?

In my code I wrote out the 'play_again' variable as shown in the video. However when I chose 'n' it comes back up and says to pick a number...I'm not sure why it keeps running. Also I should add...it only runs through the loop once after pressing 'n', on the second run it actually does exit the program.

Richard Hummel
Richard Hummel
Pro Student 5,677 Points
import random

def game_loop():
    #generate random number between 1 - 10
    random_num = random.randint(1,10)

    #limit the number of guesses
    guesses = []
    while len(guesses) < 3 :
        try:
            guess = int(input('Guess a number between 1 and 10!'))

        #catch when someone submits a non integer
        except ValueError:
            print('{} is NOT a number!'.format(guess))

        #print "too low" or "too high" msgs for bad guesses    
        else:
            if random_num == guess:
                print('You guessed correctly! My number was {}'.format(random_num))
                break

            elif guess < random_num:
                print('{} is too low...'.format(guess))

            else:
                print('{} is too high...'.format(guess))
            guesses.append(guess)

    else:
        print('Good try, but my number was {}.'.format(random_num))
    play_again = input('Do you want to play again? y/n')
    if play_again.lower() != 'n':
        game_loop()
    else:
        print('See you soon!')


game_loop()

3 Answers

andi mitre
STAFF
andi mitre
Treehouse Guest Teacher

Hey Richard,

try using raw_input instead! This may be due to your python version

play_again = raw_input('Do you want to play again? y/n')

Cheers, Andi

I have a question about Richards code. It looks to me like the second to last "else" is disjointed from any "if" statement. That I can see anyway. Am I missing something?

adham hamade
adham hamade
9,334 Points

i have the same problem and it doesn't make sense, When i press n, it just starts over and raw_input doesn't work for me.

adham, can you post your code? I finally got mine working, maybe we can figure something out together.

adham hamade
adham hamade
9,334 Points

thnx for the reply, i got it working. It was a stupid mistake where i forgot to put parenthesis next to .lower

oh yea, done that