Unbound Local error in Python I can't shake!

余生颓废 提交于 2019-12-12 06:09:32

问题


http://pastie.org/1966237

I keep getting an unbound local error. I don't understand why it occurs, if the program is running right, it should go straight into the second assignment of the print_et_list function within the main function, looping itself without actually looping. The program only quits using sys.exit() in the hey_user function.

I included the whole program for context, it isn't too long. Let me know if you want to have a look at the text files I use in the program, however I'm sure it's unlikely that it is the source of the problem.


回答1:


UnboundLocalError happens when you read the value of a local variable before you set it. Why is score a local variable rather than a global variable? Because you set it in the function. Consider these two functions:

def foo():
    print a

vs

def bar():
    a = 1
    print a

In foo(), a is global, because it is not set inside the function. In bar(), a is local. Now consider this code:

def baz():
    print a
    a = 1

Here, a is set within the function, so it's local. But it hasn't been set at the time of the print statement, so you get the UnboundLocalError.




回答2:


You forgot to pass score into hey_user().




回答3:


Looks like it's probably the score variable. It's a local in main(), but you try to reference it in hey_user().




回答4:


If you want to make score a global variable, be sure to declare it with the global statement:

def main (): global score score = 0 question, solution = print_et_list() scoresofar = hey_user (solution) print "\nYour score is now", scoresofar question, solution = print_et_list()



来源:https://stackoverflow.com/questions/6111544/unbound-local-error-in-python-i-cant-shake

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!