捕捉时解方程定义变量 python

defining variable by solving equation when catching python

我编写了一段代码,从用户那里获取方程式并分别计算右侧和左侧以检查方程式是否平衡。如果存在未定义的变量,它会捕获 NameError 异常。我想修改它以检查字典中是否仅定义了一个变量我希望程序解决该变量并将其添加到字典中。我怎样才能做到这一点? 这是我的代码

eq=input("Enter an equation")
answer=eq.split("=")
lhs=answer[0]
rhs=answer[1] 
try:
    rhs_value=eval(rhs,dict)
    lhs_value=eval(lhs,dict)
except NameError:
    print("Undefiened varaible")
else:
    if(rhs_value==lhs_value):
        print("Your equation is correct")
    else:
        print("Your equation is incorrect")

假设用户输入 Vs=(-5*g)+Vs。 g 在 dict 中定义但不是 Vs。 我希望它解决 Vs 并将其添加到字典中。 但是如果两个变量都未定义,它会打印出类似 too many variables to solve for

如果我正确理解了你的问题,这应该可以帮助你检测最多 1 个未定义的变量,并说明它:

import re
# Here I define some globals for the eval
defined_variables = {
    'g':0
}
# the expression is hardcoded in my code, but this is essentially equivalent to input()
expression = 'Vs=(-5*g)+Vs'
lhs, rhs = expression.split('=')
name_error_count = 0
while name_error_count <= 1:
    try:
        lhs_value = eval(lhs, defined_variables)
        rhs_value = eval(rhs, defined_variables)
    except NameError as e:
        name_error_count += 1
        if name_error_count > 1:
            print("Too many undefined variables")
            raise
        else:
            print(e)
            m = re.search(r"name '(\w+)' is not defined", str(e))
            undefined_variable = m.group(1)
            defined_variables[undefined_variable] = 0 # I assign None here, but you probably need to assign something else or handle this later *
            print(f'Found undefined variable {undefined_variable}, defining')
            continue # we try to get the values again
    # if we reach this point, we know we either had no problems, or at most one undefined variable
    break 
if name_error_count <= 1: # 
    # I would probably try to solve for the undefined variables here
    
    if rhs_value==lhs_value:
        print("Your equation is correct")
    else:
        print("Your equation is incorrect")