How to make a (very) simple calculator in Python using Lambda

Since beginning to learn Python a few months ago I’ve come across lots of different ways to do exactly the same thing. My question then comes “But which one is correct?” Unhelpfully I’ve found that it usually depends on circumstances and what you need it for.

I thought I’d discuss using the Lambda expression to create a simple calculator. Lambda is an anonymous one line function/expression. You can have many parameters (as many as you like), but only one expression.

You only need 3 things:

Lambda > parameters > expression

In my example I’m going to use Lambda to build a simple calculator and it’s only going to take a couple of minutes to do.

Let’s take addition. One would probably normally expect a function like this:

def sum(a,b):

return a + b

sum(3,4)

>>>>7

However, you can use one line of code to do exactly the same thing using Lambda:

add = lambda a,b: a+b

print(add(5, 6))

>>>>11

I’m defining it, like a Pandas dataframe; I’m calling Lambda; I’m showing that a and b are comma separated; then I’m telling it to print a and b, in this case 5 and 6.

You can repeat this single line of code in lots of different ways:

add = lambda a,b: a+b
multiply = lambda a,b: a*b
divide = lambda a,b: a/b
subtract = lambda a,b: a-b
mod = lambda a,b: a%b
exponent = lambda a,b: a**b
subtract = lambda a,b: a-b

(Explanation: Modulus (mod) gives the remainder of a divided by b, and exponent shows a to the power of b).

Once you’ve entered the above code you can then print whatever you’d like to see e.g.

print(mod(11, 2))

>>>>1

print(subtract(10, 1))

>>>>9

print(divide(10, 2))

>>>>5

And so on…

Happy calculating!

By Hannah Johnstone
Published
Categorized as blog

Leave a comment

Your email address will not be published. Required fields are marked *