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))
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))
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With