I am making a simple guessing game.
I have a variable inside a function called guess_left which is preset with a value. Inside the while loop, each time the person guesses wrong that value gets decremented by 1 until no more guesses are available and the loop breaks.
How do I get that decremented variable out of the loop and print it when the person wins as a winning message as in print(f"Congrats. You won with {guess_left} tries left.") Or after a certain amount of tries?
Full code:
from random import randint
def generator():
return randint(1, 1024)
def rand_guess():
random_number = generator()
guess_left = 25
flag = 0
while guess_left > 0:
guess = int(input("Please enter your lucky number: "))
if guess == random_number:
flag = 1
break
elif guess < random_number:
guess_left -= 1
print(f"Wrong Guess. Your number should be higher! You have {guess_left} tries left.")
else:
guess_left -= 1
print(f"Wrong Guess. Your number should be lower! You have {guess_left} tries left.")
if flag == 1:
return True
else:
return False
if __name__ == '__main__':
if rand_guess() is True:
print(f"Congrats! You won.")
else:
print("Sorry, you lost the game!")