[Python] Is there a way to extract a variable from an equation?

Discussão em 'Python' iniciado por Stack, Abril 29, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to make an algebraic calculator using python, with an output like so:

    eg1. x=1, x+5
    eg2. x=6+12

    So far my code looks like so:

    def algebraic_calculator():
    variables = {}
    while True:
    user_input = input("Enter expression (or 'quit' to exit): ").strip()
    if user_input.lower() == 'quit':
    break
    try:
    if '=' in user_input:
    # Handle assignment like x=1 or x=6+12
    var, expr = user_input.split('=')
    var = var.strip()
    expr = expr.strip()
    variables[var] = eval(expr, {}, variables)
    print(f"{var} = {variables[var]}")
    else:
    # Evaluate expression using stored variables
    result = eval(user_input, {}, variables)
    print(f"Result: {result}")
    except Exception as e:
    print(f"Error: {e}")

    algebraic_calculator()


    However, this does not work properly. How would I fix it?

    Continue reading...

Compartilhe esta Página