Archived
switch calculator
Now that we are more comfortable with lambdas, how could we write a calculator that takes in 2 integers, and allows performing either addition, subtraction, multiplication, or division?
Solution #1, using lambdas
1ops = {
2 '+': lambda a, b: a + b,
3 '-': lambda a, b: a - b,
4 '*': lambda a, b: a * b,
5 '/': lambda a, b: a / b
6}
7
8op = input('Enter operation: +,-,*,/')
9a = int(input('Enter first integer'))
10b = int(input('Enter second integer'))
11res = ops[op](a, b)
12print(res)
Solution #2, using operators
Python truly has thought of everything; the operator contains the operations required.
1import operator
2
3ops = {
4 "+": operator.add,
5 "-": operator.sub,
6 "/": operator.truediv,
7 "*": operator.mul
8}
9
10op = input('Enter operation: +,-,*,/')
11a = int(input('Enter first integer'))
12b = int(input('Enter second integer'))
13res = ops[op](a, b)
14print(res)
Discussion: dict as a switch statement
What we have done with:
1ops = {
2 "+": operator.add,
3 "-": operator.sub,
4 "/": operator.truediv,
5 "*": operator.mul
6}
7
8print(ops.get("+", operator.add)(1,5))
Is created a lightweight switch statement. Using dict.get even enables us to re-create the default behaviour of a traditional switch statement. Please note this is very Pythonic, so make sure the team you are working with is comfortable enough with Python before employing these types of techniques.
Conditional function call
What if we now wanted to add the numbers if a is greater than b, else subtract them?
1import operator
2
3ops = {
4 "+": operator.add,
5 "-": operator.sub,
6}
7
8a = int(input('Enter first integer'))
9b = int(input('Enter second integer'))
10res = ops['+' if a > b else '-'](a, b)
11print(res)
Since we no longer need user input for the operator, we could also express this as:
1from operator import add, sub
2
3a = int(input('Enter first integer'))
4b = int(input('Enter second integer'))
5res = (add if a > b else sub)(a, b)
6print(res)
Or using tuples as ternaries:
1from operator import add, sub
2
3a = int(input("Enter first integer"))
4b = int(input("Enter second integer"))
5res = (sub, add)[a > b](a, b)
6print(res)