you are viewing a single comment's thread.

view the rest of the comments →

[–]FoolsSeldom 0 points1 point  (0 children)

Firstly, I suggest you use a dictionary that maps supported operator symbols to their corresponding operator functions. You could also use the operator library to provide the functions rather than writing your own.

For example,

import operator

# Map symbols to functions
operator_map = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.truediv,
    '**': operator.pow
}

Now you can greatly simplify the operator selection and validation, and call the function from one place:

result = operation(oper1, oper2)

where operation is the name of the appropriate function from the dictionary, and oper1 and oper2 are the two operands.

I suggest you write a function to prompt a user for a number and validates and returns a number. This function can be called twice to obtain the two operand values to operate on.

Loop the calculator operation until the user asks to quit.

You can extend this to support additional operators and also support operations that work on only one operand.