Mar-25-2020, 04:17 AM
(This post was last modified: Mar-25-2020, 04:17 AM by deanhystad.)
You are having a problem with the scope of the variable "i". I modified your try_again function to do this:
You could do this to tell Python you want to use a variable from outside the scope of the function:
There are numerous logic errors in your program. But they are logic errors, not python errors. Do you really want to test for too many guesses in the section of code that only executes when the guess is correct?
[python]
def try_again(): while True: print('try_again', i) yes_no = input("Would you like to play again? ").lower() if yes_no == "yes": i = True else: i = FalseWhen I run the program I see this:
Output:Traceback (most recent call last):
File "C:\Users\djhys\Documents\Python\Musings\sandbox.py", line 35, in <module>
try_again()
File "C:\Users\djhys\Documents\Python\Musings\sandbox.py", line 10, in try_again
print('try_again', i)
UnboundLocalError: local variable 'i' referenced before assignment
The program crashes because there is no variable "i" in function "try_again" until the assignment i = True or i = False. The variable "i" inside of "try_again" is local to the function, and not the same "i" assigned at the top of the script. Once you leave the function that variable disappears in a puff of smoke and you are left looking at the unaltered original "i" variable.You could do this to tell Python you want to use a variable from outside the scope of the function:
def try_again(): while True: global i #<- Tell python I want to use i from the top of the script. print('try_again', i) yes_no = input("Would you like to play again? ").lower() if yes_no == "yes": i = True else: i = FalseThis lets "try_again" see the variable assigned at the top of the script, but globals should not be used to pass values out of a function. Especially not variables named "i". What is "i"? What does it mean when "i" is True? There are better ways to pass info back from the function. What if you wrote "try_again" to be like this?
def try_again(): return input("Would you like to play again? ").lower() == "yes"This would allow using "try_again()" as a Boolean value that tells you if the player wants to play again. The name "try_again" is a lot more meaningful than "i", and seeing it is a function you can go look at the function code to find out what the return value means (or you could read the doc string you are about to write).
There are numerous logic errors in your program. But they are logic errors, not python errors. Do you really want to test for too many guesses in the section of code that only executes when the guess is correct?
[python]