Python Calculator – Create a Calculator using Python

In today’s era, everyone wants to become a python expert, but how? The answer is to work on projects. In this article, TechVidvan presents a python project for beginners – Simple Calculator, so let’s start the work.

Simple Calculator in Python

Doing a mathematical calculation in your head, not trusting your answer, so you ended up using a calculator anyway. So we have just proved the importance of the simplest machine you’ve ever seen. Now let’s see how we can create this simple calculator using Python.

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

Project Prerequisites

To implement this project you need to know the following:

1. Basic concepts of Python
2. Tkinter – To create GUI

To install the libraries, you can use pip installer from the cmd/Terminal:

Pip install tkinter

Steps to Create Simple Calculator using Python

Let’s start the coding

Now, we will write the python program to create a calculator

Create main.py

Create main.py file and add the following code (alternatively, you can use the code which you downloaded in previous step):

Code:

from tkinter import *

def click(num):
global op
op=op+str(num)
iptext.set(op)

def evaluate():
global op
output=str(eval(op))
iptext.set(output)

def clearDisplay():
global op
op=""
iptext.set(op)

calc=Tk()
calc.title("TechVidvan Calculator")
op=""

iptext=StringVar()
iparea=Entry(calc,font=('large,_font',15,'bold'),bd=10,justify="right",insertwidth=4,textvariable=iptext).grid(columnspan=10)

calc.mainloop(),

Explanation:

After importing tkinter, we have defined following functions:

1. Click(num): this function takes a numeric parameter. It first converts num to string and then the function appends the string to op and displays final value of op in input area of the calculator.

2. evaluate(): This function is executed everytime the user clicks “=” i.e. when we need to evaluate the equation. Eval() is an inbuilt function in python which takes a string argument (equation) and returns a string (the output of the equation).

So this function just calls eval method and displays the output.

3. clearDisplay(): It just clears the input area.

Then we have just created an entry box to display input and output. And then finally the twelve buttons (0-9,+,-,*,/,=,C)

0-9,+,-,*,/, calls ‘click()’ when clicked.

C calls ‘clearDisplay()’.

= calls ‘evaluate()’

Summary

We have successfully developed Python calculator project, with basic concepts of Python and Tkinter.