I started learning Python yesterday; this is the first calculator I’ve made. I noticed that the last lines of code that print the equation’s result are repeated.
Can I write a function that takes the operator as input and then prints the result with just one line of code?
I imagine it would be something like this:
def result(operator):
print((str(num1)) + ” ” + str(operator) + ” ” + str(num2) + ” = ” + str(num1 insert operator to compute equation num2))
JavaScript
x
17
17
1
num1 = float(input("Enter first number: "))
2
3
op = None
4
while op not in ("-", "+", "*", "/"):
5
op = input("Enter operator (-, +, *, /): ")
6
7
num2 = float(input("Enter second number: "))
8
9
if op == "-":
10
print((str(num1)) + " " + str(op) + " " + str(num2) + " = " + str(num1 - num2))
11
elif op == "+":
12
print((str(num1)) + " " + str(op) + " " + str(num2) + " = " + str(num1 + num2))
13
elif op == "*":
14
print((str(num1)) + " " + str(op) + " " + str(num2) + " = " + str(num1 * num2))
15
elif op == "/":
16
print((str(num1)) + " " + str(op) + " " + str(num2) + " = " + str(num1 / num2))
17
Advertisement
Answer
You might try using a dictionary to map strings (operators) to function objects:
JavaScript
1
23
23
1
from operator import add, sub, mul, floordiv
2
3
operations = {
4
"+": add,
5
"-": sub,
6
"*": mul,
7
"/": floordiv
8
}
9
10
a = float(input("Enter first number: "))
11
12
while (op := input("Enter operator: ")) not in operations: pass
13
14
# 'operation' is one of the four functions - the one 'op' mapped to.
15
operation = operations[op]
16
17
b = float(input("Enter second number: "))
18
19
# perform whatever operation 'op' mapped to.
20
result = operation(a, b)
21
22
print(f"{a} {op} {b} = {result}")
23
In this case, add
, sub
, mul
and floordiv
are the function objects, each of which take two parameters, and return a number.