1

I want to use arithmetic operations in python from given tuple. Thing is i know i can use if statements for each of them and depending on user input it will give the correct answer. I don't know but is there a way to do it without ifs. I've tried with for as you can see below but I'm having trouble getting the string as an arithmetic operator.

Code:

__operators = ('+', '-', '/', '//', '*', '**', '%')

def calculator():
    x = input()
    operator = input()
    y = input()
    op = operator

    # print(str(x) + operator + str(y))

    rezultat = 0

    for operator in __operators:
        if operator in __operators:
            operator = op     


    rezultat = x + op + y       
    print(rezultat)
    return rezultat


calculator()
Stefan
  • 378
  • 2
  • 10
  • You've having trouble because it *isn't* an operator, it's just a string. Also `if operator in __operators:` seems totally pointless given that you're inside a loop `for operator in __operators:`. – jonrsharpe Mar 17 '19 at 16:31
  • @jonrsharpe Thanks for the correction. And is there a way to convert it so python will read it as an operator? – Stefan Mar 17 '19 at 16:31
  • You may want to use a dictionary that maps the operator strings to operator functions from the `operator` module. – Klaus D. Mar 17 '19 at 16:32
  • There are a couple of options. I'd recommend research, there are existing questions on how to go from a string to an operator. – jonrsharpe Mar 17 '19 at 16:32

3 Answers3

4

You can use the operator module and a dict !

import operator

op = {
    "+": operator.add
    "-": operator.sub
    "/": operator.truediv
    "//": operator.floordiv
    "*": operator.mul
    "**": operator.pow
    "%": operator.mod
}

print(op["+"](2, 3))

5

Fukiyel
  • 1,166
  • 7
  • 19
1

It is basically the same as @Fukiyel's answer, but without the use of operator module. You implement all the operations you want your calculator to support, then you create a dict with key the operator characters and value the functions:

def add(n1,n2):
    return n1 + n2

def subtract(n1,n2):
    return n1 - n2

def division(n1,n2):
    if n2 != 0:
        return n1 / n2

def integerDivision(n1,n2):
    if n2 != 0:
        return n1 // n2

def multiply(n1,n2):
    return n1 * n2

def power(n1,n2):
    return n1 ** n2

def modulo(n1,n2):
    return n1 % n2

__operators = {'+' : add, '-' : subtract, '/' : division, '//' : integerDivision, '*' : multiply, '**' : power, '%' : modulo}

def calculator():
    x = int(input())
    operator = input()
    y = int(input())

    for op in __operators:
        if operator == op:
            result = __operators[operator](x,y)
            print(result)
            return result 

calculator()
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
0

You can use eval but be careful with it, as it allows arbitrary code execution if not handled correctly.

if operator in __operators:
    rezultat = eval("x" + operator + "y")
H4kor
  • 1,552
  • 10
  • 28