I am making a custom programming language. This is a method in a class in my code. When i need to return the result, the error occurs.
UnboundLocalError: local variable 'result' referenced before assignment
def visit_BinOpNode(self, node):
left = self.visit(node.left_node)
right = self.visit(node.right_node)
if node.op_tok.value == TT_PLUS:
result = left.add_to(right)
elif node.op_tok.value == TT_MINUS:
result = left.sub_to(right)
elif node.op_tok.value == TT_MUL:
result = left.mul_to(right)
elif node.op_tok.value == TT_DIV:
result = left.div_to(right)
return result.set_pos(node.pos_start, node.pos_end)
Anyone help?
result
is not defined if none of the if statements evaluates to true, so it will error out in the last line when you try to use result
. You can set a default value like result = None
or something and check for that at the end, or you could use else
instead of else if
for the last branch.