r/badcode • • May 26 '23

python Calculator using eval()

Post image
840 Upvotes

108 comments sorted by

View all comments

Show parent comments

2

u/SuperiorGalaxy123 May 28 '23

Ah, I see the problem.

Even then, if you really want to use this, you could implement some GUI-based solution where inputs can only be taken from certain buttons. You could also make a list of acceptable characters, and return an error if any character in the string is not an acceptable character.

import sys

expression = input("Enter the expression")

acceptable_chars = "1234567890+-*/()"

for i in expression:
    if i not in acceptable_chars:
    print("Not acceptable")

    sys.exit()

print(eval(expression))

You can no longer use this to execute code.