import os
import re
def clearConsole():
# Clear the console screen based on the operating system
os.system('cls' if os.name in ('nt', 'dos') else 'clear')
def comma2Dot(value):
# Replace commas with dots in the value
return value.replace(",", ".")
def removeSpaces(value):
# Remove all spaces from the value
return re.sub(r"\s", "", value)
def insertValueFor(expression, variable, value):
# Replace variable placeholders in the expression with actual values
return expression.replace(variable, value)
# List of allowed characters in the expression
allowedCharacters = [
' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'+', '-', '*', '/', '(', ')', '.', ',', 'p', 'i', 'x', 'r'
]
while True:
# Prompt the user to input an expression
expression = input("Enter expression: ")
# Remove spaces and convert to lowercase
expression = removeSpaces(expression.lower())
if expression == "":
continue
# Replace commas with dots
expression = comma2Dot(expression)
# Check if all characters in the expression are allowed
if all(character in allowedCharacters for character in expression):
# Replace variables in the expression with user-provided values
if "x" in expression:
x = float(comma2Dot(input("Enter value for x: ")))
expression = insertValueFor(expression, "x", str(x))
if "r" in expression:
r = float(comma2Dot(input("Enter value for r: ")))
expression = insertValueFor(expression, "r", str(r))
if "pi" in expression:
expression = insertValueFor(expression, "pi", "3.14")
try:
# Evaluate and print the result of the expression
print("\n" + expression)
print(round(eval(expression), 2))
except ZeroDivisionError:
# Handle division by zero errors
print("Error: Division by zero")
except:
# Handle other errors
print("Invalid expression")
else:
# Handle special commands
if expression in ["s", "stop"]:
exit()
elif expression in ["c", "cls"]:
clearConsole()
continue
else:
# Inform the user about disallowed characters
print("The expression contains disallowed characters")
print()