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

Andreas cormack
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Andreas cormack
Python Web Development Techdegree Graduate 31,273 Points

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