11#!/usr/bin/env python3
22
3- # File: mathrepl.py
4-
53"""MathREPL, a math expression evaluator using Python's eval() and math."""
64
75import math
86
97__version__ = "1.0"
108__author__ = "Leodanis Pozo Ramos"
119
12- ALLOWED_NAMES = {name : obj for name , obj in math .__dict__ .items () if "__" not in name }
10+ ALLOWED_NAMES = {
11+ name : obj for name , obj in math .__dict__ .items ()
12+ if not name .startswith ("__" )
13+ }
1314
1415PS1 = "mr>>"
1516
2526Build math expressions using numeric values and operators.
2627Use any of the following functions and constants:
2728
28- { ', ' .join (ALLOWED_NAMES )}
29+ { ', ' .join (ALLOWED_NAMES . keys () )}
2930"""
3031
3132
32- def evaluate (expression : str ) -> float :
33+ def evaluate (expression ) :
3334 """Evaluate a math expression."""
3435 # Compile and validate syntax
3536 try :
@@ -40,13 +41,13 @@ def evaluate(expression: str) -> float:
4041 # Validate allowed names
4142 for name in code .co_names :
4243 if name not in ALLOWED_NAMES :
43- raise NameError (f' The use of " { name } " is not allowed' )
44+ raise NameError (f" The use of ' { name } ' is not allowed" )
4445
4546 return eval (code , {"__builtins__" : {}}, ALLOWED_NAMES )
4647
4748
48- def main () -> None :
49- """Main loop: Read and evaluate user input."""
49+ def main ():
50+ """Main loop: Read and evaluate user's input."""
5051 print (WELCOME )
5152 while True :
5253 # Read user's input
@@ -62,15 +63,13 @@ def main() -> None:
6263 if expression .lower () in {"quit" , "exit" }:
6364 raise SystemExit ()
6465
65- # Evaluate the expression
66+ # Evaluate the expression and print the result
6667 try :
67- result = evaluate (expression )
68+ print ( f"The result is: { evaluate (expression ) } " )
6869 except Exception as err :
70+ # Print an error message if something goes wrong
6971 print (err )
7072
71- # Print the result
72- print (f"The result is: { result } " )
73-
7473
7574if __name__ == "__main__" :
7675 main ()
0 commit comments