简体   繁体   English

为什么我收到错误:UnboundLocalError: local variable 'lcm' referenced before assignment

[英]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.

相关问题 为什么在Python中赋值之前会收到UnboundLocalError消息,该消息指出局部变量“参与者”被引用? - Why am I getting the UnboundLocalError that says local variable 'participants' referenced before assignment in Python? 我收到此错误:“UnboundLocalError:分配前引用的局部变量‘Requesting_books’” - i am getting this error : " UnboundLocalError: local variable 'Requesting_books' referenced before assignment " 我收到一个错误:“UnboundLocalError:分配前引用了局部变量'text_to_print'” - I am getting an error: “UnboundLocalError: local variable 'text_to_print' referenced before assignment” 为什么在为我的石头剪刀布代码分配之前引用了 UnboundLocalError:局部变量“last_move”? - Why am I getting an UnboundLocalError: local variable 'last_move' referenced before assignment for my rock paper scissors code? 获取 UnboundLocalError:在赋值错误之前引用了局部变量 - getting UnboundLocalError: local variable referenced before assignment error UnboundLocalError:赋值前引用的局部变量'error' - UnboundLocalError: local variable 'error' referenced before assignment UnboundLocalError: 赋值前引用的局部变量错误 - UnboundLocalError: local variable referenced before assignment error UnboundLocalError:赋值前引用了局部变量“i” - UnboundLocalError: local variable 'i' referenced before assignment 我收到错误消息:UnboundLocalError:分配前引用了本地变量'porc' - I got error : UnboundLocalError: local variable 'porc' referenced before assignment 赋值之前引用了unboundlocalerror局部变量'i' - unboundlocalerror local variable 'i' referenced before assignment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM