I am making a program that takes in a bunch of input and returns something based on it. Like if the person does 3 + 4 - (77 ** 3)
, but how can I limit it so that the person using it is only able to do that. As in, can I limit it so the person can't type in print("")
, because that will return ""
. Can I make it so that he can only do math operations? Or is that not possible and a too much of a question?
Asked
Active
Viewed 176 times
0

Sachila Ranawaka
- 39,756
- 7
- 56
- 80

Dinorami
- 29
- 9
-
1short answer: no – Daniel Sep 15 '17 at 23:11
-
Alright! Thanks for the response. :) – Dinorami Sep 15 '17 at 23:14
-
4You can limit it by not using eval and instead parsing the mathematical expression yourself. – pvg Sep 15 '17 at 23:16
-
`ast.literal_eval` is safer than `eval`. https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval. `json` is also a good tool for creating valid dictionaries and lists. `sympy` handles symbolic math. Beyond that I can imagine using `re` to test for valid characters such as the digits and `+-/*`. – hpaulj Sep 15 '17 at 23:33
-
@hpaulj really, this is a job for [`pyparsing`](https://pypi.python.org/pypi/pyparsing/1.5.7) not `re` if you want to do it right. – juanpa.arrivillaga Sep 15 '17 at 23:43
-
PLease clarify what you exactly want to have. Here we can help you resolve or improve problem and this not a coding website, please take note of it. – Jaffer Wilson Sep 16 '17 at 04:37
-
@juanpa.arrivillaga or maybe even the `numexpr` library... but that won't stop things like `987549873245987329754 ** 87345987324958732579324875932874593287459328745973259873249587324957324957932487593248759832457932875932847593287459328745932847593287459324875932847593475` going on... – Jon Clements Sep 16 '17 at 10:00
-
Thanks for anyone who responded here, but I found a much better way without using eval() or exec(). :) – Dinorami Sep 17 '17 at 12:25
-
@pvg Thanks for the response, I have actually tried something similar to what you stated! :) – Dinorami Sep 17 '17 at 12:36
1 Answers
-1
I use built in functions, like .isalpha()
, and tuples to limit the use of eval()
. I personally built a simple calculator, and limited out all words and letters via a tuple, checked by a loop over the input string.
This prevents code from being passed through, where only a mathematical function should be.
Good luck: )

user43850
- 28
- 1