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

Daniel Propp
Daniel Propp
30 Points

Repeat an if statement inside a function

Hi,

im currently on the Python Basics course and was tasked to do a number game. I went ahead to build it myself, though it took me over an hour compared to what Kenneth did in 8 minutes. Generally, would you say thats good or bad?

I also did some things differently than in his workspace, such as writing a function for playagain. Im getting a little confused though after the else statement in the playagain function. How would I make it that on the else statement it should jump back to the beginning of the function and redo the input request?

import random

def playagain():
    playagain = input("Would you like to play again? Write YES or NO: ")
    if playagain.lower() == "yes":
        game()
    elif playagain.lower() == "no":
        print("Ok, Bye!!")
    else:
        print("That isnt yes or no!")

def game():
#generate number between 1 and 10
    secret_num = random.randint(1, 10)

    guessTrials = 5 

    while guessTrials >= 1:
    #get number guess from player
    #If number isnt an integer
        try:
            guess = int(input("Guess a number between 1 and 10:"))
        except ValueError:
            print("Not a whole number!")
        else:
            #Too low/high
            if guess < secret_num:
                print("TOO LOW")

            elif guess > secret_num:
                print("TOO HIGH")

            #compare guess to secret number 
            if guess == secret_num:
                print("You got it mate!")
                playagain()

            else:
                guessTrials -= 1
                print("Thats not it. You have {} tries left".format(guessTrials))

            if guessTrials == 0:
                    print("My number was {}".format(secret_num))

game()

Thanks :)

2 Answers

Daniel Propp
Daniel Propp
30 Points

Figured it out.... Sorry!

def playagain():
    while True:
        playagain = input("Would you like to play again? Write YES or NO: ")
        if playagain.lower() == "yes":
            game()
        elif playagain.lower() == "no":
            print("Ok, Bye!!")
        else:    
            print("That isnt yes or no!")