i made an gusse counter with while loop for 3 trys and the counter stuck at 2

Viewed 30
import random
import itertools as it


def guessthenumber():
    play = input("do you want to play ?\nanswer yes or no :")
    while play != "yes" :
        if play == "no" :
            quit()
        else:
            guessthenumber()
        break


guessthenumber()
answer = random.randint(1, 5)


def random_func():
    gusse = int(input("choose a number between 0 and 10"))
    count = 3
    while gusse != answer and count != 0 :
        count -= 1
        print(count)
        print("wrong")
        random_func()
        break
    random_func()
    print("won")

Why does the guess count stop at 2 even with for loop?

1 Answers

The primary issue is as pointed out by @quamrana. When you call random_func you are adding a new stack frame that has a new count variable initialized to 3, so it immediately decrements, but then you add another call to random_func. You never return and pop this call off the stack, so there is no way to continue.

I don't see why ask if the caller wants to play. If it is the only thing the program does, running it is a pretty good indication. Also, is "gusse" a thing or just a misspelling of "guess".

You should avoid using quit() unless you are in an interpreter. You can use sys.exit, but in simple scenarios like this, returning and finishing the program is more simple.

Consider the following implementation with some slight improvements.

import random


def start(answer, tries):
    while tries:  # Continue while tries remain.
        guess = int(input("choose a number between 0 and 10: "))
        if guess == answer:
            print("won")
            return  # Just return from the function.
        tries -= 1  # Otherwise, decrement and continue.
        print(f"wrong; tries remaining: {tries}")


if __name__ == "__main__":
    answer = random.randint(1, 5)
    start(answer, 3)  # Begin the guessing part of the game.
Related