-1

I tried to make a calculator in python with out if else statements . i can't find how to fix a issue in present code

def add(n1, n2):
return n1+n2
def sub(n1, n2):
    return n1-n2
def mul(n1, n2):
    return n1*n2
def div(n1, n2):
    return n1/n2
def pow(n1, n2):
    return n1^n2
operations_and_functions= {
    "+":"add",
    "-":"sub",
    "*":"mul",
    "/":"div",
    "^":"pow",
}
num1 = int(input("What is your first number=> "))
num2 = int(input("What is your second number=> "))
for operations in operations_and_functions:
    print(operations)
***operation = str(input("What operation do you want to do=> "))
calculation = operations_and_functions[operation](num1,num2)***
answer = calculation(num1,num2)
print(f"{num1} {calculation} {num2} is equal to {answer}")

I can't convert this code" [operations_and_functionsoperation" into "add(num1,num2)"

Abdul Haq
  • 62
  • 1
  • 7

1 Answers1

2

The values of your dict should be the functions themselves, not strings. Also, don't call the result again:

from operator import add, sub, mul, truediv, pow

operations_and_functions= {
    "+": add,
    "-": sub,
    "*": mul,
    "/": truediv,
    "^": pow,
}
num1 = 3
num2 = 5
operations_and_functions["+"](num1,num2)
# 8
operations_and_functions["-"](num1,num2)
# -2
operations_and_functions["*"](num1,num2)
# 15
operations_and_functions["/"](num1,num2)
# 0.6
operations_and_functions["^"](num1,num2)
# 243

You can of course define the functions yourself, as you did. One fix there:

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

In Python, ^ is the bitwise XOR operator.

user2390182
  • 72,016
  • 6
  • 67
  • 89