Home > OS >  Why does my code return a whole number even when it's not supposed to?
Why does my code return a whole number even when it's not supposed to?

Time:04-18

I'm doing a kata in Codewars where you have to make a function that takes in a string that is operator-like (Essentially the function takes in an operator-like string, for example, " " and have to convert it to the matching operator, in this case, the Plus operator), and 2 values, value1 and value2. Then, the function is supposed to turn those 3 into an equation and return the result of that equation (E.g: func(" ", 50, 20) returns 70).

Screenshot: A screenshot

The code:

def basic_op(operator, value1, value2):
    opFuncs = {" ": (lambda x,y: x y),
           "-": (lambda x,y: x-y),
           "*": (lambda x,y: x*y),
           "/": (lambda x,y: x/y)
          }
    return int(opFuncs[operator] (value1, value2))

And everything else seems to go well except the error in red included in the screenshot. So in that instance my function returned 0 but it must be 0.005101.... Any idea what is happening here?

CodePudding user response:

You are returning: int(opFuncs[operator] (value1, value2))

the int() is making your return value an integer, meaning it is discarding the decimal places.

Try returning: float(opFuncs[operator] (value1, value2))

  • Related