[英]Why am I getting the error: UnboundLocalError: local variable 'lcm' referenced before assignment
I am trying to find the lcm of two numbers.我试图找到两个数字的 lcm。 But when I run the program, I am getting the error:
但是当我运行程序时,我得到了错误:
UnboundLocalError: local variable 'lcm' referenced before assignment
UnboundLocalError:分配前引用的局部变量“lcm”
Why am I getting this error?为什么我会收到此错误? I can't understand what is wrong with my code.
我不明白我的代码有什么问题。
Here's my code:这是我的代码:
def compute_lcm( num1, num2):
if num1 > num2:
greater = num1
else:
greater = num2
for i in range(1, greater + 1):
if ( i % num1 ) == 0 and ( i % num2) == 0:
lcm = i
print(lcm)
compute_lcm( 12, 14)
The error you get is because the code never satisfies i % num1 == 0 and i % num2 == 0
, and thus never sets a value for the lcm.您得到的错误是因为代码永远不会满足
i % num1 == 0 and i % num2 == 0
,因此永远不会为 lcm 设置值。 Also notice that the second part of the code must be outside the if/else
.另请注意,代码的第二部分必须在
if/else
之外。
def compute_lcm(num1, num2):
if num1 > num2:
greater = num1
else:
greater = num2
lcm = None
for i in range(1, greater + 1):
if i % num1 == 0 and i % num2 == 0:
lcm = i
print(lcm)
compute_lcm(12, 14) # >>> None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.