Learn to Code via Tutorials on Repl.it!

← Back to all posts
Let's make a simple postfix calculator in Python!
Wumi4 (531)

Let's make a simple postfix calculator in Python!

Hello everyone!

It is a very long time since I post my last post. So yeah, I come back here.

In this tutorial, we will learn about how to make a simple postfix calculator in the Python programming language.

Ok, let's get into it!

First, what is a postfix calculator?

A postfix calculator (also known as Reverse Polish Notation calculator, or RPN calculator) is a calculator. The difference is that if you, for example, want to calculate the sum of 2 and 3, instead of writing 2 + 3, you will write 2 3 + instead. The same with other operators, 2 3 + 4 * will equal to (2 + 3) * 4.

So, why make one, you may ask?

Well, it's because making a postfix calculator will teach you a lot, it will teach you how to take input, how to use stack, switch-case (in case that the language you use support it), and some more. It is also not very time-consuming (a simple postfix calculator can be made in just a few hours, and in just a few minutes if you already master how to make it). Also, I encourage you to make this program as a start to any programming language you learn if you are an intermediate programmer, because it will teach you a lot and can be a good base to start that language.

Ok, enough saying, let's get started!

Setup

Setup for this program is simple: Create a directory that will contain the program, create main.py (which contains the program) inside the directory, and that's it.

Calculator

Now, open main.py using your favorite editor, and we will start making the calculator.

First, let's create the Calculator class. This class will contain a stack, some helper functions, and will run our code.

class Calculator:  
	def __init__(self):  
		self.stack = []
		self.token_map = {...}
		
	def push(self, sth):  
		self.stack.append(int(sth))
		
	def pop(self):
		return self.stack.pop()
		
	def print(self):
		print(self.pop())
		
	def run(self, code):
		pass

As you can see, our class has the stack (self.stack), and 4 methods: push will "push" a number to the stack, pop will "pop" the last element from the stack, print will "pop", then print, and the last one, run, will run our code.

self.token_map is a little bit special, I will explain later.

Now, let's add some code to run, delete pass inside run and type:

	tokens = code.split(" ")

In here, we will split code into pieces based on the whitespace (), so if our code is:

5 5 + print

tokens will be:

["5", "5", "+", "print"]

This process is called lex (or tokenize), and it is a crucial part in any programming language. Of course, the lexing process that we are doing today is very different to the lexing process that you see in other programming languages. And our process is also very simple and primitive, while still enough for our calculator.

On the run method, after the declaration of tokens, we will declare a variable called c:

	c = 0

c will be our "pointer", points to each token in the tokens.

After that, type:

	while c < len(tokens):
		current = tokens[c]

This will create a while loop that will never stop until c is larger (or equal) to the length of tokens. We will also declare a variable called current, it contains the cth token in tokens.

Inside the loop, we will make a short if-else chain:

		if current.isnumeric():
			self.push(current)
			c += 1
		elif current in self.token_map:  
			pass
		else:
			raise SyntaxError(f"{current}: Invalid syntax.")

In here, if current is numeric (aka contains only numbers), then we will push it to the stack. And increase c by 1, so we can consume the next token.

On the elif part, we will check if current is in self.token_map or not, now go back to where self.token_map was declared, and fill the dictionary with:

{
	"+": lambda: self.push(self.pop() + self.pop()),
	"-": lambda: self.push(self.pop() - self.pop()),
	"*": lambda: self.push(self.pop() * self.pop()),
	"/": lambda: self.push(self.pop() / self.pop()),
	"print": lambda: self.print()
}

Then go back to the elif, and fill it with:

			self.tokens_map[current]()
			c += 1

This will run the lambda that has current as the key in the token map (and that's why we need the parenthesis), and again, increase c by 1.

To try out the calculator, at the outside of the Calculator class, make a new Calculator, then use the run method.

calc = Calculator()
calc.run("5 5 + print")

If all works well, you should see 10 in your terminal after run the program.

And that's our calculator! You might be a little bit confusing after making it, but that's OK! If you practice enough and have a little bit research (maybe about stack and programming languages), then you might understand how does this calculator work.

REPL

Now, this will be our final part. It is not required, but it is quite important, and that is the REPL!

REPL (Read-Evalulate-Print-Loop) is something like the prompt when you run python in your terminal. It reads your input, then evaluates (aka run) the input, then prints the result, and continues to read your input, becomes a loop.

This part is really easy to make:

def repl():
	calc = Calculator()
	while True:
		inpt = input(">> ")
		calc.run(inpt)

Now, to run our REPL every time we run the program, and this final line:

if __name__ == "__main__":  
	repl()

Andddddddddd that's our REPL! When you run the program using python3 main.py, you should see a prompt like this:

>> 

The end

And that's all for today's tutorial! Thank you for reading it! I hope you enjoy it! Stay safe and have a nice day!

:)

Comments
hotnewtop
ch1ck3n (2052)

i understand litterly nothign but i can see this is no ordinary calculator soooo

updoot