Mar-25-2020, 02:47 AM
Hello everyone, I am new to python and decided to create a guessing game. So imported the random module and the user must guess a number between 1 - 9. Simple right. For some reason, I am having trouble because I created a try again function where after the user exceeds 5 tries or if they guessed the correct number the program asked them if they want to play again. I want everyone's input on what went wrong. Again I am new and am still learning, however, I am a sponge that wants to learn. Any advice is greatly appreciated! Thank you!
import random as random
i = True
guess_count = 0
leftover = 5
def try_again():
while True:
yes_no = input("Would you like to play again? ").lower()
if yes_no == "yes":
i = True
else:
i = False
while i: # while i is equal to true
user_guess = int(input("Choose a number from 1 - 9: ")) # User inputs a number
cpu_num = random.randint(1,9)
if (user_guess != cpu_num) and (guess_count < 5): # user guess does not equal to computer number and guess count is less than 5
if user_guess < cpu_num: # user guess is lower than computer number
print(f"{user_guess} is too low of a guess. You have " + str(leftover) + " guesses left.")
guess_count += 1 # increment by one
leftover -= 1 # decrease by one
else: # user guess is higher than computer number
print(f"{user_guess} is too high of a guess. You have " + str(leftover) + " guesses left")
guess_count += 1 # increment by one
leftover -= 1 # decrease by one
else: # if user is correct
print("You are Dj Khaled. All you do is WIN! ") # you won
i = False
try_again()
if guess_count > 5: # track the guess count
print("Out of guesses. Would you like to try again? ") # prompt to try again
print(cpu_num)
i = False
