0

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.

user3839821
  • 107
  • 1
  • 10
  • `global guesses_so_far` should help – Marcin Dec 05 '14 at 01:12
  • @Marcin looks like its a duplicate, but I still don't understand why it is skipping through the defined function. However, I do now understand that I will need to use the global version to determine if their have been sufficient guesses to fail the player. – user3839821 Dec 05 '14 at 01:20
  • have a look at my recent [anwser](http://stackoverflow.com/questions/27306212/remember-array-value-after-function-call/27306259#27306259). I guess its similar problem what you have. – Marcin Dec 05 '14 at 01:33

0 Answers0