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 Python Basics (2015) Number Game App Number Game Refinement

while loop end but game() wont start again

import random

secret_number = random.randint(1, 20)
guesses = []

def game():
    while len(guesses) < 5:
        print(secret_number)
        print(guesses)
        try:
            guess = int(input("Guess Number Between 1 to 20: "))
        except ValueError:
            print("Please enter only number...")
            continue
        else:
            if guess == secret_number:
                print("Well done you got it...")
                break
            elif guess > secret_number:
                print("number little higher")
            elif guess < secret_number:
                print("number little lower")
            guesses.append(guess)


    else:
        print(guesses)
        play_again = input("do you wanna play agan Y/n: ")
        if play_again.lower() != 'n':
            game()

        else:
            print("bye bye")
game()

in the end yes or no is not working

[MARKDOWN ADDED BY MOD]

Could you please format your code with "" (look in the Markdwon Cheatsheet) The lines before the "" must be free it is a pain to format Python code :)

2 Answers

Hi syalih

If you put the guesses list inside the function game it will work.

import random

secret_number = random.randint(1, 20)


def game():
    guesses = [] # set guesses here 
    while len(guesses) < 5:
        print(secret_number)
        print(guesses)
        try:
            guess = int(input("Guess Number Between 1 to 20: "))
        except ValueError:
            print("Please enter only number...")
            continue
        else:
            if guess == secret_number:
                print("Well done you got it...")
                break
            elif guess > secret_number:
                print("number little higher")
            elif guess < secret_number:
                print("number little lower")
            guesses.append(guess)


    else:
        print(guesses)
        play_again = input("do you wanna play agan Y/n: ")
        if play_again.lower() != 'n':
            # when you call the function game() length of guesses is still 5 so the else statement gets executed
           game()

        else:
            print("bye bye")
game()

Thanks :)