vendredi 15 avril 2022

How to stop function from going back in without calling quit()

so I've been trying to make a little number-guessing game where the user guesses a number and the computer basically says whether that's higher/lower than the correct number or if it's correct.Basically, everything works correctly up until the user enters an invalid input(anything that isn't an integer). Then it still works correctly but when you eventually guess the right number it tells you that you won and the number of tries that you took būt it also returns a Typerror which says that strings and ints cannot be compared. This is weird because it doesn't do it as soon as you enter the invalid input but rather at the end when you get it correct. Additionally, it shouldn't even be doing that as there is no part in the else statement that tells it to go back into the function.

from random import randint
def game(rand_num = randint(1,10),trys=1): #generates random number and sets trys to 1
    user_guess = input('enter your guess 1-10:') #user guess
    try: # try except to check for validity of input,restarts functions with preserved random number and # of tries
        user_guess = int(user_guess)
    except:
        print('please try again and enter a valid input')
        game(rand_num=rand_num,trys=trys)
    
        # if and elif to check if the number was higher or lower,if it was then it will restart the game function with preserved random number
        # and trys increased by 1
    if user_guess < rand_num: 
        print('your guess was lower than the magic number so try again')
        game(rand_num=rand_num,trys=trys+1)
    elif user_guess > rand_num:
        print('your guess was higher than the magic number so try again')
        game(rand_num=rand_num,trys=trys+1)
    else: #if both don't work then you must have won and it tells you that as well as how many trys you took``
        print('hurray you won!!!!!')
        print(f'you took {trys} trys')
    
game()

example of user interactions in the console

Also when I tried to use a breakpoint to determine the issue, again everything seemed fine until after it told the that they won,it mysteriously just went back into the function and started doing stuff with the previously invalid input set as the user_guess variable which is presumably why the Type error happened.

the first place where the function "goes" to after telling the user they won

the first place where the function "goes" to after telling the user they won

the 2nd place where it "goes"

the 2nd place where it "goes"

It does that for a few more times but yeah it just basically cycles through if elif and try except for some reason

however, I found out that you can use a quit() at the end of the else statement that tells the user they won to solve this but as far as I know that just suppresses the function from doing anything and exits it so it isn't really a solution.




Aucun commentaire:

Enregistrer un commentaire