Skip to content

Commit d10ccf9

Browse files
authored
TR second update
1 parent 2f012e8 commit d10ccf9

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

python-eval-mathrepl/mathrepl.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,8 @@
3131

3232
def evaluate(expression):
3333
"""Evaluate a math expression."""
34-
# Compile and validate syntax
35-
try:
36-
code = compile(expression, "<string>", "eval")
37-
except SyntaxError:
38-
raise SyntaxError("Invalid input expression")
34+
# Compile the expression (eventually raising a SyntaxError)
35+
code = compile(expression, "<string>", "eval")
3936

4037
# Validate allowed names
4138
for name in code.co_names:
@@ -62,12 +59,20 @@ def main():
6259
if expression.lower() in {"quit", "exit"}:
6360
raise SystemExit()
6461

65-
# Evaluate the expression and print the result
62+
# Evaluate the expression and handle errors
6663
try:
67-
print(f"The result is: {evaluate(expression)}")
68-
except Exception as err:
69-
# Print an error message if something goes wrong
64+
result = evaluate(expression)
65+
except SyntaxError:
66+
# If the user enters an invalid expression
67+
print("Invalid input expression syntax")
68+
continue
69+
except NameError as err:
70+
# If the user tries to use a name that isn't allowed
7071
print(err)
72+
continue
73+
74+
# Print the result if no error occurs
75+
print(f"The result is: {result}")
7176

7277

7378
if __name__ == "__main__":

0 commit comments

Comments
 (0)