r/learnpython • u/iloveduasidhafhuisd • 9d ago
can i make the exec() command only execute if the code is functional and wont return an error?
So i want to make something where you can input() a math problem and get an answer thru the text output, but if there is a syntax error, i want it to just reopen the prompt instead of crashing, is there a way that i can check if the code is valid before executing? thanks!
0
Upvotes
12
u/Discordbothost 9d ago
to answer the literal question: yes, you can check the syntax without running anything. ast.parse just reads the text and raises SyntaxError if it isn't valid. and since it gives you the parsed tree, you can also reject anything that isn't plain math, which fixes the delete-your-files problem people mentioned:
then your loop catches (SyntaxError, ValueError, ZeroDivisionError) and asks again. 1/0 is valid syntax so that one only shows up when it runs, that's why it's in the list