Skip to content

Commit e221e8b

Browse files
authored
Fix invalid input for math functions
1 parent d10ccf9 commit e221e8b

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

python-eval-mathrepl/mathrepl.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,18 @@
3131

3232
def evaluate(expression):
3333
"""Evaluate a math expression."""
34-
# Compile the expression (eventually raising a SyntaxError)
34+
# Compile the expression eventually raising a SyntaxError
35+
# when the user enters an invalid expression
3536
code = compile(expression, "<string>", "eval")
3637

3738
# Validate allowed names
3839
for name in code.co_names:
3940
if name not in ALLOWED_NAMES:
4041
raise NameError(f"The use of '{name}' is not allowed")
4142

43+
# Evaluate the expression eventually raising a ValueError
44+
# when the user uses a math function with a wrong input value
45+
# e.g. math.sqrt(-10)
4246
return eval(code, {"__builtins__": {}}, ALLOWED_NAMES)
4347

4448

@@ -66,8 +70,9 @@ def main():
6670
# If the user enters an invalid expression
6771
print("Invalid input expression syntax")
6872
continue
69-
except NameError as err:
73+
except (NameError, ValueError) as err:
7074
# If the user tries to use a name that isn't allowed
75+
# or an invalid value to a given math function
7176
print(err)
7277
continue
7378

0 commit comments

Comments
 (0)