Ad
Mathematics
Fundamentals

Code that can take an integer, an operator, and another integer, in that order, and return 'the answer'.
For example, can take '3' '*' and '3' to give '9'.

Did I do it right? Is this kumite?

Code
Diff
  • def calculator(a,b,c):
    	try: return eval(str(a)+str(b)+str(c))
    	except ZeroDivisionError: return float('inf')
    • def calculator(sign:str = '+', n1:(float | int) = 0, n2:(float | int) = 0, exceptions_allowed: bool = False):
    • """The simplest calculator ever.
    • First argument is sign, +, -, *, /, ** and % supported. Default is +.
    • The next two arguments is n1 and n2. Integers, Floats and Complex numbers supported. Their defaults is 0.
    • Other arguments is options.
    • exceptions_allowed - if True, will return exception instead of 0 when error occurs. Default is False."""
    • if not isinstance(sign, str):
    • if not exceptions_allowed: return 0
    • else: raise TypeError('Type of the sign must be string.')
    • if not isinstance(n1, (int, float, complex)):
    • if not exceptions_allowed: return 0
    • else: raise TypeError('Type of the first number must be int, float or complex.')
    • if not isinstance(n2, (int, float, complex)):
    • if not exceptions_allowed: return 0
    • else: raise TypeError('Type of the second number must be int, float or complex.')
    • if sign not in "+-*/**%":
    • if not exceptions_allowed: return 0
    • else: raise TypeError('Sign must be +, -, *, /, ** or %.')
    • if sign == "/" and n2 == 0:
    • if not exceptions_allowed: return float('inf') #mathematically this is better, than x/0=0
    • else: raise ZeroDivisionError('Can\'t divide by zero.')
    • return eval(str(n1) + sign + str(n2)) #using universal and optimized, but dangerous and bugged solution
    • def calculator(a,b,c):
    • try: return eval(str(a)+str(b)+str(c))
    • except ZeroDivisionError: return float('inf')