Development of a calculator in Python: difficulties in implementing the eval function

53 views Asked by At

I'm building a calculator in Python. I'm following a tutorial on the internet, it's really cool to take the course. But on this code page, eval is a little complicated to make it part of the code.

def _eq(self):
    displayText = self.display.text()

    if not isValidNumber(displayText):
        print('Sem nada para a direita')
        return

    self._right = float(displayText)
    self.equation = f'{self._left} {self._op} {self._right}'
    result = 0.0

    try:
        result = eval(self.equation)
    except ZeroDivisionError:
        print('Zero Division Error')

    self.display.clear()
    self.info.setText(f'{self.equation} = {result}')
    self._left = result
    self._right = None

I used some codes that I tried to generate through gpt chat, but the results are similar. The biggest problem is in this line of code:

result = eval(self.equation)
1

There are 1 answers

0
Balduin Scheffbuch On

I do not know what the rest of your code looks like, but in the snipped you shared, it seems like you have not yet defined self._left. It would also be helpful to know what kind of error you are getting.

Besides, you should consider using an alternative to eval() as it can run arbitrary code, which is considered to be a security vulnerability. Furthermore, it might have an impact on your performance as it is parsing and interpreting new code at runtime.

It might be beneficial to write your method that evaluates the equation instead of using eval().

The method could look something like the following:

def evaluate_expression(left_operand, operator, right_operand):
    # addition
    if operator == '+':
        return left_operand + right_operand
    # subtraction
    elif operator == '-':
        return left_operand - right_operand
    # multiplication
    elif operator == '*':
        return left_operand * right_operand
    # division
    elif operator == '/':
        try:
            return left_operand / right_operand
        except ZeroDivisionError:
            print('Zero Division Error')
            return None
    # other operands you might want to implement
    else:
        print('Unsupported operator')
        return None

Edit: You might want to parse the operands into integers or floats and the operator to a string.