Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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 :)