-1
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?

theherk
  • 6,954
  • 3
  • 27
  • 52
TUSK ACT 4
  • 15
  • 2

1 Answers1

0

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.
theherk
  • 6,954
  • 3
  • 27
  • 52
  • 1
    thank you that was very helpful i add the ask for playing cause im just practicing and want to develop my range and yes gusse is a misspelling of guess hhhh i want to know one thing what is the purpose of the line "if __name__ == "__main__" : " cause it seems the program run fine without it . – TUSK ACT 4 Sep 07 '22 at 22:50
  • @TUSKACT4: [Here is an excellent answer on if __name__ == "__main__"](https://stackoverflow.com/a/419185/2081835). Basically, it prevents this code from running if the module is imported. – theherk Sep 08 '22 at 06:29