Python - UnboundedLocalError -
import random def hilo(usernum, ran, c): c = c + 1 if ran > usernum: newnum = input("higher: ") hilo(int(newnum), ran, c) elif ran < usernum: newnum = input("lower: ") hilo(int(newnum), ran, c) else: print("that's it! took you", c, "tries!") def easylevel(): choice = input("\ntry , guess random number(1-10): ") if not choice: print("you need make guess. try again.") easylevel() else: choicenum = int(choice) if choicenum < 1 or choicenum > 10: print("that out of range. try again!") easylevel() count = 0 randnum = int(random.random() * 10 + 1) hilo(choicenum, randnum, count) #checks if user inputs out of range def checklevel(level, low, high): if level > high or level < low: print("that out of range. try again!") main() def main(): print("\n ::: welcome guessing game! ::: \n") print("1 - hard(100) 2 - medium(20) 3 - easy(10)") level = input("choose level play: ") if not level: print("you need choose level. try again.") main() level = int(level) #check level out of range checklevel(level, 1, 3); if level == 1: hilevel() elif level == 2: medlevel() else: easylevel() main()
the code above giving me following error:
traceback (most recent call last): file "c:/users/daniel/pycharmprojects/guessing game/guessing_1.py", line 61, in <module> main() file "c:/users/daniel/pycharmprojects/guessing game/guessing_1.py", line 47, in main main() file "c:/users/daniel/pycharmprojects/guessing game/guessing_1.py", line 59, in main easylevel() file "c:/users/daniel/pycharmprojects/guessing game/guessing_1.py", line 24, in easylevel if choicenum < 1 or choicenum > 10: unboundlocalerror: local variable 'choicenum' referenced before assignment
process finished exit code 1
take @ line 24. not sure why it's giving me error.
when call easylevel, if goes if statement instead of else statement, choicenum
variable undefined because set in else statement. should initialize choicenum in beginning or set choicenum in if statement well
if not choice: print("you need make guess. try again.") easylevel() choicenum = 0 #declare choice num or return else: choicenum = int(choice)
Comments
Post a Comment