Making a Calculator Program in Python
Introduction
Python programming language is a great programming language for performing numerical operations and evaluating mathematical expressions.
Using this powerful feature, we can develop useful programs that work in daily life.
In this article, we will make a calculator application with you. This application will be a command line calculator program.
This calculator will initially only be able to perform basic arithmetic operations (addition, subtraction, multiplication, division, etc.).
but at the end of the guide, how to improve this code
You will also find ideas. So we will create a solid foundation for an even more advanced calculator.
We will use these basic Python components when creating this calculator:
- Mathematical operators (
+,-,*,/etc.) - Variables (to store user entered data)
- Conditional statements (if–elif–else) (to determine which action to take)
- Functions (to make our code organized and reusable)
- User input (to allow the user to enter transactions and numbers)
By combining all these parts, we will make a mini calculator** that works entirely from the command line.
Step 1 — Getting User Input
A calculator works best for solving human input operations.
So the first step in our program is to have the user enter the numbers and the action.
First, we will create a Python file for our program.
In this example, we name our file hesapmakinesi.py.
If you want, you can use nano, VS Code or another text editor:
nano hesapmakinesi.py
Now let's add the codes to our file that will run the program.
In this example we will ask the user for two numbers.
We can use Python's built-in input() function for this.
This function takes user input from the keyboard and allows us to store the entered value in a variable.
We can tell the user what to enter by adding a text (string) in parentheses.
It's also a good habit to put a space ( ) at the end of the question to prevent user input and text from getting stuck together.
sayi1 = input("Birinci sayıyı girin: ")
sayi2 = input("İkinci sayıyı girin: ")
After writing these two lines, don't forget to save your program.
If you are using the nano editor:
- Press CTRL + X,
- then confirm the save by pressing Y,
- and exit with ENTER.
Now let's run the program from the terminal:
python calculator.py
When you run this command, the program in the terminal will ask you to log in:
Birinci sayıyı girin: 5
İkinci sayıyı girin: 7
If you run the program a few times and try inputs other than numbers, you'll notice that Python accepts them.
This is because the input() function takes all input as string (text).
So Python doesn't assume that you actually entered number; He/she thinks you are just writing a text.
So, before operating with this data, we need to convert the inputs to numerical values.
There are two main reasons why we want to convert inputs to numbers in this program:
-
To perform mathematical operations:
Python must be able to perform addition, subtraction, or multiplication correctly.
This is only possible when the data is of numeric type (int or float). -
To verify that user input is a valid number:
If the user accidentally enters letters or symbols,
the program should be able to detect this and handle the error properly.
According to the needs of the calculator, the string value from the input() function
You can convert it to integer data type or decimal number.
Since we will only be working with integers in this example, we wrap the function input() with int()
user input convert
and we will convert it to type integer (int):
sayi1 = int(input("Birinci sayıyı girin: "))
sayi2 = int(input("İkinci sayıyı girin: "))
Now when you run the program and enter two integers, you won't get any errors.
Birinci sayıyı girin: 5
İkinci sayıyı girin: 7
However, if you enter a letter, symbol, or non-integer value, Python throws the following error:
ValueError: invalid literal for int() with base 10: 'a'
So far, you have received input from the user as integers and defined two variables to store it as data types.
Step 2 — Adding Operators
Before completing the program, we will add a total of four mathematical operators:
+→ collection-→ subtraction*→ bump/→ division
Thanks to these operators, our calculator will now be able to perform basic arithmetic operations.
When developing the program, it is important to make sure that each part works correctly.
So let's start with addition process.
So that the user can see the results, we will add the two numbers print() inside the function:
sayi1 = int(input("Birinci sayıyı girin: "))
sayi2 = int(input("İkinci sayıyı girin: "))
print(sayi1 + sayi2)
Now run the program and enter the desired 2 numbers and see the result.
Birinci sayıyı girin: 5
İkinci sayıyı girin: 7
12
The program's output shows that the process is working correctly.
Now let's provide the user with more understandable feedback throughout the program.
To do this, we can use string formatting.
This way we can clearly show the user what numbers he entered, which operator was used, and the result obtained.
sayi1 = int(input("Birinci sayıyı girin: "))
sayi2 = int(input("İkinci sayıyı girin: "))
print(f"{sayi1} + {sayi2} işleminin sonucu: {sayi1 + sayi2}")
Now when he runs the program again, the user will see an additional output where he can verify the mathematical operation performed:
Birinci sayıyı girin: 5
İkinci sayıyı girin: 7
5 + 7 işleminin sonucu: 12
Using string formatting gives the user clearer feedback about the action taken.
Now at this point, you can add other operators. By preserving the format you used for the collection,
Let's include subtraction, multiplication and division operations in the program:
sayi1 = int(input("Birinci sayıyı girin: "))
sayi2 = int(input("İkinci sayıyı girin: "))
print(f"{sayi1} + {sayi2} = {sayi1 + sayi2}")
print(f"{sayi1} - {sayi2} = {sayi1 - sayi2}")
print(f"{sayi1} * {sayi2} = {sayi1 * sayi2}")
print(f"{sayi1} / {sayi2} = {sayi1 / sayi2}")
Here, you also added the remaining operators (-, *, /) to your program.
If you run the program now, all these processes will run at the same time.
However, our goal is to give the user the right to choose a single action. So the program should only perform one action at a time.
To achieve this, we will use conditional statements (if–elif–else).
Thanks to these structures, the program will perform only that operation whichever operator the user chooses.
Step 3 — Add Conditionals (if–elif–else)
Now the purpose of our hesapmakinesi.py program is to
allowing the user to choose between different arithmetic operators.
For this, we will add an information text at the top of the program, telling the user what to do and including the making a choice section.
We can use triple quotes to write multiple lines of text:
print("""
Lütfen yapmak istediğiniz işlemi seçin:
1. Toplama (+)
2. Çıkarma (-)
3. Çarpma (*)
4. Bölme (/)
""")
In this program, users can specify which action they want to take.
Will use operator symbols (+, -, *, /).
For example, if the user wants to perform subtraction, he/she will enter -.
Since we will receive a transaction selection from the user, we will use the input() function again.
We will store this input in a variable:
islem = input("Yapmak istediğiniz işlemi girin (+, -, *, /): ")
sayi1 = int(input("Birinci sayıyı girin: "))
sayi2 = int(input("İkinci sayıyı girin: "))
print(f"{sayi1} + {sayi2} = {sayi1 + sayi2}")
print(f"{sayi1} - {sayi2} = {sayi1 - sayi2}")
print(f"{sayi1} * {sayi2} = {sayi1 * sayi2}")
print(f"{sayi1} / {sayi2} = {sayi1 / sayi2}")
At this point, if you run the program, no matter what you type on the first input screen, nothing will happen. Because we haven't added conditionals (if–elif–else) yet.
To solve this problem, we will define a separate condition for each operator:
if→ will perform addition,elif→ will manage subtraction, multiplication and division operations,else→ will give an error message when the user enters an invalid operator.
islem = input('''
Lütfen yapmak istediğiniz işlemi seçin:
+ → Toplama
- → Çıkarma
* → Çarpma
/ → Bölme
''')
sayi1 = int(input("Birinci sayıyı girin: "))
sayi2 = int(input("İkinci sayıyı girin: "))
if islem == "+":
print(f"{sayi1} + {sayi2} = {sayi1 + sayi2}")
elif islem == "-":
print(f"{sayi1} - {sayi2} = {sayi1 - sayi2}")
elif islem == "*":
print(f"{sayi1} * {sayi2} = {sayi1 * sayi2}")
elif islem == "/":
print(f"{sayi1} / {sayi2} = {sayi1 / sayi2}")
else:
print("Geçersiz bir işlem seçtiniz! Lütfen +, -, * veya / girin.")
Let's examine step by step how the program works.
-
The program first asks the user to enter an action symbol.
For example, the user types*(multiplication operation). -
Then it asks for two numbers.
Let's say the user enters 15 and 25 respectively. -
At this point, the program prints the operation and the result on the screen:
Lütfen yapmak istediğiniz işlemi seçin:
+ → Toplama
- → Çıkarma
* → Çarpma
/ → Bölme
Birinci sayıyı girin: 15
İkinci sayıyı girin: 25
15 * 25 = 375
Due to the nature of the program, if the user enters an invalid character, such as %, in the initial action selection screen,
The program will show the error only after entering the numbers.
This may negatively affect the user experience.
Therefore, to better manage different scenarios, input validation or
You may consider improvements such as don't ask again if you make a wrong choice.
The program you have created up to this point is fully functional. It can successfully perform addition, subtraction, multiplication and division operations.
However, it can currently perform a one-time calculation.
When you want to perform a new operation, you need to rerun the program.
In the next step, we will define a few functions to solve this situation.
In this way, the program will be able to perform more than one operation if the user wishes.
Step 4 — Defining Functions
We will now add functions to our code so that the user can run the program as many times as he wants.
As a first step, let's wrap the existing code block into a function. We will call this function calculate().
The codes inside the function must be written one level inside.
Also, for the program to actually run, you need to add it to the bottom of the file.
We need to call(call) the function.
def calculate():
islem = input('''
Lütfen yapmak istediğiniz işlemi seçin:
+ → Toplama
- → Çıkarma
* → Çarpma
/ → Bölme
''')
sayi1 = int(input("Birinci sayıyı girin: "))
sayi2 = int(input("İkinci sayıyı girin: "))
if islem == "+":
print(f"{sayi1} + {sayi2} = {sayi1 + sayi2}")
elif islem == "-":
print(f"{sayi1} - {sayi2} = {sayi1 - sayi2}")
elif islem == "*":
print(f"{sayi1} * {sayi2} = {sayi1 * sayi2}")
elif islem == "/":
print(f"{sayi1} / {sayi2} = {sayi1 / sayi2}")
else:
print("Geçersiz bir işlem seçtiniz! Lütfen +, -, * veya / girin.")
# Fonksiyonu çağır
calculate()
Now let's create our second function.
This function will ask if the user wants to recalculate. 🔁
We will build this structure again with condition statements (if, elif, else).
This time we will only have three states:
- If the user says yes, the program will run again.
- If no is said, the program will end,
- If he writes anything else, it will give an error message and ask again.
The name of the function will be again() and will be added after the block def calculate()::
# Kullanıcıya hesap makinesini tekrar kullanmak isteyip istemediğini soran fonksiyon
def again():
# Kullanıcıdan giriş al
tekrar = input('''
Yeni bir işlem yapmak ister misiniz?
Evet için E, Hayır için H tuşlayın:
''')
# Eğer kullanıcı 'E' yazarsa hesaplamayı yeniden başlat
if tekrar.upper() == 'E':
calculate()
# Eğer kullanıcı 'H' yazarsa programı sonlandır
elif tekrar.upper() == 'H':
print('Görüşmek üzere! 👋')
# Geçersiz bir giriş olursa tekrar sor
else:
print("Geçersiz giriş! Lütfen 'E' veya 'H' girin.")
again()
# calculate() fonksiyonunu programın sonunda çağır
calculate()
Although the else structure above catches incorrect inputs, the user can use the upper case difference instead of “Yes / No”.
May also give short answers like “y/n” or “Y/N”.
To make this more user friendly
We can use the functions str.upper() or str.lower().
def again():
tekrar = input('''
Yeni bir işlem yapmak ister misiniz?
Evet için E, Hayır için H tuşlayın:
''')
# Küçük veya büyük harf fark etmeksizin 'E' kabul edilir
if tekrar.upper() == 'E':
calculate() # Hesaplamayı yeniden başlat
# Küçük veya büyük harf fark etmeksizin 'H' kabul edilir
elif tekrar.upper() == 'H':
print('Görüşmek üzere! 👋')
else:
print("Geçersiz giriş! Lütfen 'E' veya 'H' girin.")
again() # Hatalı girişte yeniden sor
At this point, you must add the again() function to the end of the calculate() function to run the code that asks the user if they want to continue.
def calculate():
islem = input('''
Lütfen yapmak istediğiniz işlemi seçin:
+ → Toplama
- → Çıkarma
* → Çarpma
/ → Bölme
''')
sayi1 = int(input("Birinci sayıyı girin: "))
sayi2 = int(input("İkinci sayıyı girin: "))
if islem == "+":
print(f"{sayi1} + {sayi2} = {sayi1 + sayi2}")
elif islem == "-":
print(f"{sayi1} - {sayi2} = {sayi1 - sayi2}")
elif islem == "*":
print(f"{sayi1} * {sayi2} = {sayi1 * sayi2}")
elif islem == "/":
print(f"{sayi1} / {sayi2} = {sayi1 / sayi2}")
else:
print("Geçersiz bir işlem seçtiniz! Lütfen +, -, * veya / girin.")
# ✅ Her işlemden sonra tekrar sorma fonksiyonunu çağır
again()
def again():
tekrar = input('''
Yeni bir işlem yapmak ister misiniz?
Evet için E, Hayır için H tuşlayın:
''')
if tekrar.upper() == 'E':
calculate()
elif tekrar.upper() == 'H':
print('Görüşmek üzere! 👋')
else:
print("Geçersiz giriş! Lütfen 'E' veya 'H' girin.")
again()
# Programın başlangıç noktası
calculate()
You can now start your program by running the python hesapmakinesi.py command in your terminal window and perform as many operations as you want.
Step 5 — Developing the Code
Now you have a very nice, fully working program.
But there is much more you can do to improve this code.
For example, you can add a welcome function at the top of the program that welcomes the user.
This function can show a welcome message to the user when the program is started.
def welcome():
print('''
==============================
Python Hesap Makinesine Hoş Geldin!
==============================
''')
# Program başlarken çalıştır
welcome()
calculate()
There are opportunities to add more error-handling to the overall program.
For example, even if an invalid value such as "plankton" is entered when requesting a number from the user
You can keep the program running without crashing.
If sayi1 and sayi2 are not integers currently in the program, the user will receive an error
and the program stops completely.
Additionally, if the user selects division ( / ) and enters 0 as the second number,
the following error occurs:
ZeroDivisionError: division by zero
In this exercise we were limited to only four operators,
However, you can add more mathematical operators to the program if you want.
islem = input('''
Lütfen yapmak istediğiniz işlemi seçin:
+ → Toplama
- → Çıkarma
* → Çarpma
/ → Bölme
** → Üs Alma
% → Mod (Kalan Bulma)
''')
Additionally, you may want to rewrite certain parts of the program with a **loop structure.
In this way, the code becomes more organized and the user can perform operations over and over again.
There is no need to run the program from scratch.
In every programming project, it's important to handle bugs, improve code, and
There is more than one way to improve.
Keep in mind: When writing code, the important thing is not to find the “perfect solution”,
To be able to produce a solution that works and can be improved.
Result
In this tutorial, we will show you how to create a simple calculator program running on the command line.
You learned step by step how to create it.
Now you can improve the code based on this example and add new features
and you can start other projects that require user interaction with peace of mind.

