## Calculator

#### by Josh Blake (Y12 age ~17)

Josh is a highly talented self-taught programmer. He recommends Think Python - How to think like a computer scientist

This Python calculator uses a dictionary in which each value is a tuple comprising a function and an integer. This simpler example of the dictionary in use should help you to understand the code.

import operator #A dictionary storing each mathematical operator symbol as a key and a #tuple (comprising a function and an integer) as its value. The integer is used #by the calculator as a measure of the precedence of the operator. operators = { '+': (operator.add, 5), '-': (operator.sub, 5), '*': (operator.mul, 10), '/': (operator.truediv, 10), '^': (operator.pow, 15), } #Access the second item in the (zero-based) tuple. print (operators['+']) #Pass the integers 35 and 7 to the add function (the first item in the tuple). print (operators['+'](35, 17)) #Pass the integers 6 and 7 to the multiply function print (operators['*'](6, 7)) #Pass the integers 2 and 5 to the power function print (operators['^'](2, 5))

The output is: ## The Code

Note the excellent use of error trapping throughout this program.