Untitled

 avatar
unknown
plain_text
3 months ago
1.8 kB
4
Indexable
import math

# Store user-defined functions
user_functions = {}

def evaluate_expression(expression):
    """Evaluate a mathematical expression safely."""
    try:
        # Allow math functions
        allowed_names = {name: getattr(math, name) for name in dir(math) if not name.startswith("__")}
        
        # Include user-defined functions
        allowed_names.update(user_functions)
        
        return eval(expression, {"__builtins__": {}}, allowed_names)
    except Exception as e:
        return f"Error: {e}"

def define_function(name, params, expression):
    """Define a user function."""
    try:
        # Create a lambda function dynamically
        func_code = f"lambda {', '.join(params)}: {expression}"
        user_functions[name] = eval(func_code, {"__builtins__": {}}, user_functions)
        return f"Function '{name}' defined."
    except Exception as e:
        return f"Error: {e}"

def calculator():
    """Simple programmable calculator REPL."""
    print("Programmable Calculator (type 'exit' to quit)")
    
    while True:
        command = input(">>> ").strip()
        
        if command.lower() == "exit":
            break
        elif command.startswith("def "):
            try:
                # Parse function definition
                parts = command[4:].split("=", 1)
                header, expression = parts[0].strip(), parts[1].strip()
                name, param_str = header.split("(", 1)
                params = param_str.rstrip(")").split(",") if param_str.rstrip(")") else []
                name = name.strip()
                
                print(define_function(name, params, expression))
            except Exception as e:
                print(f"Error: {e}")
        else:
            print(evaluate_expression(command))

if __name__ == "__main__":
    calculator()
Editor is loading...
Leave a Comment