[英]Why am I getting an unboundLocalError?
Error I am getting is: 我得到的错误是:
UnboundLocalError: local variable referenced before assignment? UnboundLocalError:分配前引用的局部变量?
Code: 码:
def menu_option(index, count):
import random
random_number1 = random.randrange(1,31)
random_number2 = random.randrange(1,31)
if index == 1:
problem = random_number1 + random_number2
elif index == 2:
problem = random_number1 - random_number2
elif index == 3:
problem = random_number1 * random_number2
elif index == 4:
problem = random_number1 // random_number2
elif index == 5:
problem = random_number1 % random_number2
user_solution = get_user_solution(problem)
return check_solution(user_solution, solution, count)
在最后一行return check_solution(user_solution, solution, count)
solution
变量未定义
Like Himanshu said It is because you have used a variable solution
to which you haven't done any assignment. 就像Himanshu所说的,这是因为您使用了变量solution
,但尚未对其进行任何分配。 So in this case python looks for it inside function if not, it will look for it in global. 因此,在这种情况下,python会在函数内部寻找它,如果不是,它将在全局中寻找它。 if it doesn't find any assignment to it before being used it raises UnboundLocalError
, also the variable problem
is confined to if block so i think it is not accessible outside. 如果它在使用前没有找到任何赋值,则会引发UnboundLocalError
,变量problem
也仅限于if块,因此我认为它在外部是不可访问的。 So assign problem
with some value before nested if block and also check solution
variable about what should be assigned before passing it in function. 因此,在嵌套if块之前给problem
分配一些值,并在传递给函数之前检查solution
变量应分配的内容。
The chain of if/elif/elif ...
suppose none of those conditions are met? if/elif/elif ...
链if/elif/elif ...
假设没有一个条件被满足? Then problem
is not assigned. 然后problem
没有分配。 But you try to use it in user_solution = get_user_solution(problem)
. 但是您尝试在user_solution = get_user_solution(problem)
使用它。 Looks like problem
is the problem. 看起来problem
就是问题。 The solution depends on what your design says should happen in this case. 解决方案取决于您的设计在这种情况下应该执行的操作。 Is there a default that should be used? 是否应使用默认值? Raise your own exception? 提出自己的例外情况? Return an error code? 返回错误代码? You have to decide that. 您必须决定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.