Basic Calculator in Python

Basic Calculator in Python

Hey everyone, I hope you all are doing great today. So, without wasting any time let's start with today's article where I will show you how you can create a basic calculator using Python language. Today I won't be taking any extra time as I did in my last article where I showed you how to make a password generator and I also tried to explain why you might need one, etc. But I think there is no need to tell you why you might need a calculator and again even if you don't it will help to brush up your python skills. Okay enough talk let's start coding.

Coding

It will not be a GUI application although we can create a GUI calculator with python as well, I'll cover that in a future article.

And I will be diving the code into 3-4 parts in this article as well so that I can easily make you understand what's going on in the code.

Part-1

import os
logo = """
 _____________________
|  _________________  |
| | Pythonista      | |  .----------------.  .----------------.  .----------------.  .----------------.
| |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |
|  ___ ___ ___   ___  | | |     ______   | || |      __      | || |   _____      | || |     ______   | |
| | 7 | 8 | 9 | | + | | | |   .' ___  |  | || |     /  \     | || |  |_   _|     | || |   .' ___  |  | |
| |___|___|___| |___| | | |  / .'   \_|  | || |    / /\ \    | || |    | |       | || |  / .'   \_|  | |
| | 4 | 5 | 6 | | - | | | |  | |         | || |   / ____ \   | || |    | |   _   | || |  | |         | |
| |___|___|___| |___| | | |  \ `.___.'\  | || | _/ /    \ \_ | || |   _| |__/ |  | || |  \ `.___.'\  | |
| | 1 | 2 | 3 | | x | | | |   `._____.'  | || ||____|  |____|| || |  |________|  | || |   `._____.'  | |
| |___|___|___| |___| | | |              | || |              | || |              | || |              | |
| | . | 0 | = | | / | | | '--------------' || '--------------' || '--------------' || '--------------' |
| |___|___|___| |___| |  '----------------'  '----------------'  '----------------'  '----------------'
|_____________________|
"""

In the first line, you can see that I have imported the os module of Python, it is used when we want to perform some tasks that are related to our Operating System and can not be directly done using Python. (We will use the "cls" clear screen command of windows in our code using the os module)

now if you want to know what are modules and why we need to import them. I have already covered that in a previous article you can check it out here.

I got the ASCII art from here.

Part-2

def sub(num1, num2):
    return num1 - num2


def mul(num1, num2):
    return num1 * num2


def div(num1, num2):
    return num1 / num2


def add(num1, num2):
    return num1 + num2

In the above code snippet, you can see the basic syntax of how we define a function in Python. We simply write "def" then function name and then give some parameters inside the parenthesis, then inside the function, we do some tasks and then finally, we return a value. I recommend you to read more about functions in Python using this link.

And as you can see I have written 4 functions for the basic math operations, I did so because In programming we follow a practice called DRY or Don't Repeat Yourself this simply means that if there is a part of code that is repeating, again and again, we should write inside of a function instead of writing it again and again, this is not forced on anyone but it is considered as a good practice because it makes our code more readable and which sometimes is very helpful to find bugs (errors) in our code.

As we will be using these mathematical operations many times in our code that's why I put them in a different function.

Part-3

def calculator():
    print(logo)
    first_num = float(input("First Number?: "))
    while True:
        operation = input("+\n-\n*\n/\nOperation: ")
        second_num = float(input(f"{first_num} {operation} "))
        operations = {
            "+": add(first_num, second_num),
            "-": sub(first_num, second_num),
            "*": mul(first_num, second_num),
            "/": div(first_num, second_num)
        }

        print(f"{first_num} {operation} {second_num} = {operations[operation]}")
        first_num = operations[operation]
        print()
        if input(f"Type 'y' to continue with {first_num} or 'n' to start new calculation: ").lower() == "n":
            print()
            os.system("cls")
            calculator()


calculator()

In the last part, we write the main logic of our program. First, we print the logo that we defined above.

After that, we ask the user to input the first number and store it into a variable named "first_num".

Then inside of an infinite loop (will come to it later). We ask the user to enter the operation they would like to perform and store it into a variable named "operation". Then, we ask the user to input the second number and we store it in a variable named "second_num". As we have got the two numbers and the operation It's time to compare the operation entered with the operations inside the "operations" Dictionary and call a function accordingly which will return the correct answer, store it in the variable first_num (will tell why later) and we print that to the user.

Now back to the infinite loop, an infinite loop is a loop that runs forever and never stops, I used an infinite loop because I wanted this calculator to continuously run and not close after every calculation (You can change that if you want). So in the end, we ask the user if they want a new calculation or if they want to continue with their previous calculation. Now, you see if the user chooses to start a new calculation we use our os module and clear the entire screen and calls the calculator function again and if the user selects to continue with the previous calculation We have already changed the first_num to the result we got at the end and now our program will continue running the infinite while loop.

Complete Code

import os
logo = """
 _____________________
|  _________________  |
| | Pythonista      | |  .----------------.  .----------------.  .----------------.  .----------------.
| |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |
|  ___ ___ ___   ___  | | |     ______   | || |      __      | || |   _____      | || |     ______   | |
| | 7 | 8 | 9 | | + | | | |   .' ___  |  | || |     /  \     | || |  |_   _|     | || |   .' ___  |  | |
| |___|___|___| |___| | | |  / .'   \_|  | || |    / /\ \    | || |    | |       | || |  / .'   \_|  | |
| | 4 | 5 | 6 | | - | | | |  | |         | || |   / ____ \   | || |    | |   _   | || |  | |         | |
| |___|___|___| |___| | | |  \ `.___.'\  | || | _/ /    \ \_ | || |   _| |__/ |  | || |  \ `.___.'\  | |
| | 1 | 2 | 3 | | x | | | |   `._____.'  | || ||____|  |____|| || |  |________|  | || |   `._____.'  | |
| |___|___|___| |___| | | |              | || |              | || |              | || |              | |
| | . | 0 | = | | / | | | '--------------' || '--------------' || '--------------' || '--------------' |
| |___|___|___| |___| |  '----------------'  '----------------'  '----------------'  '----------------'
|_____________________|
"""



def sub(num1, num2):
    return num1 - num2


def mul(num1, num2):
    return num1 * num2


def div(num1, num2):
    return num1 / num2


def add(num1, num2):
    return num1 + num2


def calculator():
    print(logo)
    first_num = float(input("First Number?: "))
    while True:
        operation = input("+\n-\n*\n/\nOperation: ")
        second_num = float(input(f"{first_num} {operation} "))
        operations = {
            "+": add(first_num, second_num),
            "-": sub(first_num, second_num),
            "*": mul(first_num, second_num),
            "/": div(first_num, second_num)
        }

        print(f"{first_num} {operation} {second_num} = {operations[operation]}")
        first_num = operations[operation]
        print()
        if input(f"Type 'y' to continue with {first_num} or 'n' to start new calculation: ").lower() == "n":
            print()
            os.system("cls")
            calculator()


calculator()

CONCLUSION

I hope this article would help you and if there is anything that you didn't understand or maybe I wrote something wrong tell me by commenting below. And please try to change the code in some way or another and make it a bit different from mine, it will help you to learn a lot.

Best of luck 💯