# Python Calculator

Many programmers try to learn programming languages by writing simple enough programs. One possibility is to write a calculator. Of course, you can calculate in the Python debugger or by running the console. But it’s much better to write your own calculator in python with a graphical interface.

## Use the console to do the math

To calculate mathematical expressions you can run the console. Run python. Then type in the mathematical expressions and get the answer. You don’t even need to know how to program. ## Making a simple calculator

The best way to strengthen your knowledge of programming by writing simple programs. You can think of many such applications – a calendar, a program for storing notes, getting the weather forecast. You can write a program that takes screenshots and saves the images into a folder. In any case, you need to choose some simple task, so as not to get buried in it. Then it can be expanded to make a really useful application. In this case, we’ll see how to create a simple graphical calculator in Python 3. To implement the graphical interface we will use the standard Tkinter package. This package is included in Python 3. So, if you have Python installed, you don’t need to install anything additionally. In the first lines of calculator.py file plug in the library functions:

• Tkinter for the graphical interface;
• Decimal for calculations with higher precision, since float accuracy is not enough.

### Import libraries and source data

Create application window – object Tk with title Calculator. In the sub tuple buttons we’ll store the labels for the buttons. In the stack list we are going to add typed numbers and operations to be performed. activeStr is designed to store the typed number.

```from tkinter import *
from decimal import *

root = Tk()
root.title('Calculator')

buttons = (('7', '8', '9', '/', '4'),
('4', '5', '6', '*', '4'),
('1', '2', '3', '-', '4'),
('0', '.', '=', '+', '4')
)

activeStr = ''
stack = []```

### Calculate result

The calculate function gets the operands from the stack list and the operation to be performed on them. The result is displayed in the label inscription. We will get strings from the list using the pop method.

```def calculate():
global stack
global label
result = 0
operand2 = Decimal(stack.pop())
operation = stack.pop()
operand1 = Decimal(stack.pop())

if operation == '+':
result = operand1 + operand2
if operation == '-':
result = operand1 - operand2
if operation == '/':
result = operand1 / operand2
if operation == '*':
result = operand1 * operand2
label.configure(text=str(result))```

### Handling clicks

The click function processes the pressed key. The text displayed on the button pressed is passed as its argument. It is a good idea to store the entered value directly in the text instead of creating a separate variable for it. But it doesn’t work this way because of the work algorithm. After the result is calculated, it is written in the inscription. If you tried to enter a new number after that, it would overwrite the previous result. In the list with operators and commands for the calculator does not have to be 3. But when processing with the pop method, the last 3 values entered would be considered. And after the calculation is done, the list will be cleared. Then the result is added to it, in case the user presses the operation key on the calculator at once instead of entering a new number.

```def click(text):
global activeStr
global stack
if text == 'CE':
stack.clear()
activeStr = ''
label.configure(text='0')
elif '0' <= text <= '9':
activeStr += text
label.configure(text=activeStr)
elif text == ':
if activeStr.find('.') == -1:
activeStr += text
label.configure(text=activeStr)
else:
if len(stack) >= 2:
stack.append(label['text'])
calculate()
stack.clear()
stack.append(label['text'])
activeStr = ''
if text != '=':
stack.append(text)
else:
if text != '=':
stack.append(label['text'])
stack.append(text)
activeStr = ''
label.configure(text='0')```

### Appearance

Now let’s start designing the look of the calculator and how buttons are handled. Create a caption to display typed values and results. In this loop we create buttons. The location of the buttons and the inscription is done in tabular form, using the grid packer. And finally we run the event loop mainloop.

```label = Label(root, text='0', width=35)
label.grid(row=0, column=0, columnspan=4, sticky="nsew")

button = Button(root, text='CE', command=lambda text='CE': click(text))
button.grid(row=1, column=3, sticky="nsew")
for row in range(4):
for col in range(4):
button = Button(root, text=buttons[row][col],
command=lambda row=row, col=col: click(buttons[row][col])
button.grid(row=row + 2, column=col, sticky="nsew")

root.grid_rowconfigure(6, weight=1)
root.grid_columnconfigure(4, weight=1)

root.mainloop()```

The inscription has a width of 35, in order to make the design of the buttons fit the inscription. And as a result the buttons look better with this value. In order to make the buttons work properly, I had to create a different function for each button using lambda. Similar to the above python calculator code, we can make a calendar, for example. To do this, we need to ask the operating system for the current date. Open the desired month, calculate which numbers fall on Mondays, which year is leap year. Make it possible to change the year and months.