未验证 提交 d10ccf9e 编写于 作者: L Leodanis Pozo Ramos 提交者: GitHub

TR second update

上级 2f012e8a
...@@ -31,11 +31,8 @@ Use any of the following functions and constants: ...@@ -31,11 +31,8 @@ Use any of the following functions and constants:
def evaluate(expression): def evaluate(expression):
"""Evaluate a math expression.""" """Evaluate a math expression."""
# Compile and validate syntax # Compile the expression (eventually raising a SyntaxError)
try: code = compile(expression, "<string>", "eval")
code = compile(expression, "<string>", "eval")
except SyntaxError:
raise SyntaxError("Invalid input expression")
# Validate allowed names # Validate allowed names
for name in code.co_names: for name in code.co_names:
...@@ -62,12 +59,20 @@ def main(): ...@@ -62,12 +59,20 @@ def main():
if expression.lower() in {"quit", "exit"}: if expression.lower() in {"quit", "exit"}:
raise SystemExit() raise SystemExit()
# Evaluate the expression and print the result # Evaluate the expression and handle errors
try: try:
print(f"The result is: {evaluate(expression)}") result = evaluate(expression)
except Exception as err: except SyntaxError:
# Print an error message if something goes wrong # If the user enters an invalid expression
print("Invalid input expression syntax")
continue
except NameError as err:
# If the user tries to use a name that isn't allowed
print(err) print(err)
continue
# Print the result if no error occurs
print(f"The result is: {result}")
if __name__ == "__main__": if __name__ == "__main__":
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册