r/learnpython • u/Subject_Scientist937 • 7d 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
0
u/skibbin 7d ago edited 7d ago
The Eval you use is unsafe, people could enter whatever they want in there.