Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store and use mathematical operators as python variable [duplicate]

Tags:

python

I am new to python and was trying to write something like this below (code A) so it does eactly like code B. I want to make use of user input of mathematical operators as do_what variable. How can we write this code (A) in python so it would work like code B?

code A

num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
do_what = input("Enter a calculation symbol for calculation you want to perform: ")
result = float(num1) do_what float(num2)
print("result is: " + str(result))

code B

num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = int(num1) + int(num2)
print("result is: " + str(result))
like image 772
MAPK Avatar asked Dec 03 '22 18:12

MAPK


2 Answers

You can use the operator module for common operators and make a lookup dictionary to map symbols to functions. If you want operators not in that module, you can simply define custom functions and add look them up the same way:

import operator

operatorlookup = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.truediv
}

num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
do_what = input("Enter calculation symbols for calculation you want to perform: ")

op = operatorlookup.get(do_what)

if op is not None:
    result = op(float(num1), float(num2))
else:
    result = "Unknown operator"
print("result is: " + str(result))
like image 131
Mark Avatar answered Jan 12 '23 00:01

Mark


You might also be interested in knowing about the inbuilt function eval. This reduces the if and else loops to a single statement for this particular example of yours

num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
do_what = input("Enter calculation symbols for calculation you want to perform: ")

result = eval(num1 + do_what + num2)
print("result is: %s" %result)

# Enter a number: 3
# Enter another number: 18
# Enter calculation symbols for calculation you want to perform: *
# result is: 54

EDIT

To make eval slightly safe in this particular case, you can perhaps use something like this

if do_what in ['+', '-', '*', '**', '/']:
    result = eval(num1 + do_what + num2)
    print("result is: %s" %result)
else:
    print ("Enter an arithmetic operator")
like image 30
Sheldore Avatar answered Jan 12 '23 01:01

Sheldore