Skip to content Skip to sidebar Skip to footer

Is This An Efficient Calculator In Python?

Is this an efficient calculator in Python? def calculator(): print('\nBasic Calculator.\n') num_1 = input('Enter your first number: ') operation = input('Enter your

Solution 1:

You can use eval()

a = 1
b = 2
operation = '/'print(eval(f'{a}{operation}{b}'))
0.5

Handle shenanigans by users:

a = 1
b = 0
operation = '/'try:
    print(eval(f'{a}{operation}{b}'))
except Exception as exp:
    print(exp)

Solution 2:

Here is another basic example:

operations = {
    '+': lambda x, y: x + y,
    '-': lambda x, y: x - y,
    '*': lambda x, y: x * y,
    '/': lambda x, y: x / y,
}

try:
    x, sign, y = input("Enter expression separated by whitespace(ex: 2 + 3): ").split()
    if sign == '0':
        breakelse:
        print(operations[sign](int(x), int(y)))
except (ValueError, KeyError, ZeroDivisionError):
    print("Something went wrong, check your input")

Solution 3:

It's decent, but reviews of working code belong on CodeReview.SE, not here.

  • Call the result variable result instead of sum, that obviously only is meaningful for addition.
  • As per AlexanderLekontsev's answer, you don't need a huge big if...else ladder that always computes result and prints the output. A dispatch dictionary to (binary or unary) lambda function is better. You could have all the functions be binary, and default arg2=None, that way you can handle unary functions.
  • You're assuming the user types in valid floats in response to num_1, num_2. But what if they press return? or type pi or e? or 'help' or :-D etc. You should catch the exception ValueError: could not convert string to floatand display the user's invalid input back to them, "expected a number"(/"operator").
    • You only need num_2 if operation is a binary not a unary operation, but future stuff like sqrt, log, log10, trigonometrics (sin, cos, tan), hyperbolics and their inverses (arc-fns) are all unary operations. Just something to keep in mind for the future. Don't hardwire your parser to one expected input sequence.
    • Inputting numbers could get more complicated in future. What if you wanted to support both hexadecimal 7e8 and float/general/exponential notation 7e8? You might need multiple try...except clauses. You might add a HEX mode in future. But then you'll need to generalize from num1 to say arg1, and if arg1 == HEX then enable(/toggle) hex mode, and recurse/loop.
  • Suggest printing print("Invalid Operation: must be +,-,*,/,..."), this actually tells the user which operations are legal. So: % isn't, neither is ^, neither is log, cos, sqrt etc.
  • So if you implement the above, you can support things like e^x
  • Supporting parentheses would require recursion.

Solution 4:

Try this:

defcalculate(num1, num2, operator):
    operator = operator.strip()
    if operator.strip() in ['+', '-', '*', '/']:
        if operator == '/'andeval(num2) == 0:
            returnNonetry:
        result = eval(f'float({num1.strip()}) {operator} float({num2.strip()})')
    except:
        return""return result

num1 = '3'
num2 = '5'
operator =  '+'

result = calculate(num1, num2, operator)

if result == '':
    print('Wrong expression !')
elif result == None:
    print('Dive bye zero !')
else:
    print(f'The answe is {result} !')

Solution 5:

Your code is alright but we can improvise by using eval()

print(" Basic Calculator ")
i = ""while i != 'exit':
    i = input(" Enter the expression to evaluate or type 'exit' to exit : ")
    print(eval(i))

Post a Comment for "Is This An Efficient Calculator In Python?"