Why does it skip through the defined function without running it?
The goal is to call the last if and else conditionals only after everything_but_the_end() has run, however the program just skips them. My code was running fine before I made the function (so that I could call it back to replay), but now it is not running as intended.
import random
rand_num = random.randint(1, 10)
guesses_total = 5
guesses_so_far = 0
def everything_but_the_end():
while guesses_so_far < 5:
print("Hi, I'm thinking of a number, 1 - 10.")
guess = int(input("Guess what number I am thinking of: "))
if guess == rand_num:
guesses_so_far = guesses_so_far + 1
break
elif guess < rand_num:
guesses_so_far = guesses_so_far + 1
print("Too Low \n--- Attempt {}".format(guesses_so_far))
elif guess > rand_num:
guesses_so_far = guesses_so_far + 1
print("Too High \n--- Attempt {}".format(guesses_so_far))
if guesses_so_far > 4:
play_again_lost = input("Sorry, you lost. Play again? Y or N: ")
if play_again .upper() == "Y":
everything_but_the_end()
else:
print("Okay, goodbye!")
quit()
else:
play_again = input("Congrats! You won! Want to play again? Y or N: ")
if play_again .upper() == "Y":
everything_but_the_end()
else:
print("Okay, goodbye!")
quit()
I thought to solve it by just putting everything_but_the_end() after I defined it, but it gives me two errors, that
Traceback (most recent call last):
File "/Users/danielternyak/Google Drive/PythonPrograms3.4/randnum.py", line 24, in <module>
everything_but_the_end()
File "/Users/danielternyak/Google Drive/PythonPrograms3.4/randnum.py", line 11, in everything_but_the_end
while guesses_so_far < 5:
UnboundLocalError: local variable 'guesses_so_far' referenced before assignment
I am unsure why I am receiving this error, as I have already defined guesses_so_far at the very top of the page.