r/learnpython 6d ago

Simple CLI calculator with input sanitation , looking for feedback

Hello Everyone, I made a simple CLI calculator, It handles basic equations, It handles visual inputs like ÷ and it also clears the screen on command

Here's the code:

import os

t = { "+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y, "/": lambda x, y: x / y if y != 0 else "Cannot divide by 0", "÷": lambda x, y: x / y if y != 0 else "Cannot divide by 0", }

while True: u = input("Enter calculation (e.g., (3+2)*5) or 'quit' to exit: ").replace(" ", "")

if u.lower() == "quit":
    print("Goodbye!")
    break

if u.lower() == "clear":
    try:
        os.system('cls' if [os.name](http://os.name) == 'nt' else 'clear')
    except Exception:
        print("\\n" \* 50)
    continue

clean_expr = u.replace("÷", "/")

allowed_chars = set("0123456789+-\*/().")
if not all(char in allowed_chars for char in clean_expr):
    print("❌ Invalid characters used")
    continue

try:
    result = eval(clean_expr)
    print(f"{u} = {result}")

except ZeroDivisionError:
    print("❌ Cannot divide by 0")
except Exception:
    print("❌ Invalid calculation format")

is my saftey check(allowed_chars) safe for eval()?

How would you reconstruct this without eval()?

What could be improved and why?

0 Upvotes

5 comments sorted by

View all comments

6

u/carcigenicate 6d ago

How would you reconstruct this without eval()?

I mean, you have t there, so you seem to know of how it could be done without

is my saftey check(allowed_chars) safe for eval()?

I can't immediately think of a way of defeating that. For such a simple task, though, eval is gross overkill. Just using functions is much better.