dimanche 25 juillet 2021

Why does my output execute multiple print functions?

I'm new to programming and I'm working on a guessing game where the user inputs a number until they get it correct. I'm trying to understand why my output creates multiple print functions if I don't guess in the first try. But if I guess the answer correctly on first try, it prints correctly.

ans = 5

def function(guess, ans):
    if ans != guess:
        if ans < guess:
            print("Guess lower")
            return False
        elif ans > guess:
            print("Guess higher")
            return False
    elif ans == guess:
        print("Correct!")

def init():
    print("Guess a number between 1 and 10: ")
    guess = int(input())
    main(guess)

def main(guess):
    while function(guess, ans) == False:  
        init()
        function(guess, ans)
        break

init()

Outputs:

Correct guess on first attempt: correct on first attempt

Correct guess on third attempt: correct on third attempt

Aucun commentaire:

Enregistrer un commentaire