Riko
Riko

Reputation: 19

Write a function that calculates an operation result given 2 numbers and the operator

I have tried this, but the problem is I don't know how to make the function identify math operations like + or -

def calc(n1,n2,"x"):
    y= n1 x n2
    return y 

Upvotes: 0

Views: 3375

Answers (4)

Mr. Xcoder
Mr. Xcoder

Reputation: 4795

The safest, although not the most convenient solution is to define a function that does the work "by hand":

def calculate(num1,num2,sign):
    if sign == "+":
        return num1 + num2
    elif sign == "-":
        return num1 - num2
    elif sign == "*":
        return num1 * num2 #multiplication
    elif sign == "**":
        return num1 ** num2 #powers
    elif sign == "/" or sign == ":":
        return float(num1) / float(num2) #division
    elif sign == "%":
        return num1 % num2
    else:
        raise Exception('Invalid operator in use') # handling invalid signs

Usage: print(calculate(3,2,"*")) # prints 6

I really prefer this solution, because you can perform custom operations and you can add as many as you want. For invalid signs, this throws an Exception.


Hope it helps!

Upvotes: 0

MariusSiuram
MariusSiuram

Reputation: 3634

Use operator.* and a map:

import operator

operators = {"+": operator.add,
             "-": operator.sub,
             "*": operator.mul,
             "/": operator.div}

def calc(n1, n2, op):
    return operators[op](n1, n2)

Addendum:

Note that I initially only wrote those four operators, but with this approach any two-number-operation can be easily added (remainder, boolean operations...). More ad hoc operations can be added by implementing the function, like:

import random
import operator

def dice_thrower(n_dice, dice_size):
    return sum(random.randint(1, dice_size)
               for _ in range(n_dice))

operators = {"+": operator.add,
             "-": operator.sub,
             "*": operator.mul,
             "/": operator.div,
             "d": dice_thrower}
...
# unchanged `calc` function

Upvotes: 2

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

Three solutions:

Solution #1 : do a test on your 'operator' value:

if operator == '+':
    return n1 + n2
elif operator == '-':
    return n1 - n2
# etc

Solution #2: Python functions are objects so you can build an 'operator=> function" dict (using lambda makes it even easier):

OPERATIONS = {
    "+" : lambda n1, n2 : n1 + n2,
    "-" : lambda n1, n2 : n1 - n2,
    "*" : lambda n1, n2 : n1 * n2,
    "/" : lambda n1, n2 : n1 / n2,
    }

def calc(n1,n n2, operator):
    return OPERATIONS[operator](n1, n2)

Solution #3: do the same thing using the operator module that already provides operators as functions:

import operator

OPERATIONS = {
    "+" : operator.add,
    "-" : operator.sub,
    "*" : operator.mul,
    "/" : operator.div,
    }

Upvotes: 1

Binyamin Even
Binyamin Even

Reputation: 3382

use eval:

def calc(n1,n2,operator):
    return eval(str(n1)+operator+str(n2))

result:

 calc(2,5,"-")
 >>-3

Upvotes: 0

Related Questions