GITHUB REPO | FOLLOW ME ON -> TWITTER | LINKEDIN

Build Your Own Multi-Functional Python Calculator Using Math

The goal of this project is to create a calculator in Python by applying math operations and an ASCII graphics library. This article will demonstrate to you how to create a Python program that can perform basic mathematical operations and contains features such as exponentiation, logarithm, and square root.

Al-Junaed Islam

--

Photo by iSawRed on Unsplash

Step-by-Step Code Explanation

The first thing we need to do is set up our Python Multi-Function Calculator. Open up your preferred code editor, create a new file, and save it with a descriptive name such as “multi_function_calculator.py.”. Also, create other files which will be used as modules calculator_art.py

calculator_art.py

logo = """
-----------------------
| _________________ |
| | Calculator | |
| | By AJBrohi | |
| |_________________| |
| ___ ___ ___ ___ |
| | 7 | 8 | 9 | | + | |
| |___|___|___| |___| |
| | 4 | 5 | 6 | | - | |
| |___|___|___| |___| |
| | 1 | 2 | 3 | | x | |
| |___|___|___| |___| |
| | . | 0 | = | | / | |
| |___|___|___| |___| |
| |
-----------------------
"""

multi_function_calculator.py

Firstly, the required libraries, i.e., math and os, and the ASCII art logo are imported. The math library is used to perform mathematical operations, while the os library is used to clear the console output. The art logo gives the calculator a professional touch.

import math, os, art

The program defines a few basic arithmetic functions, including add, subtract, multiply, and division. Then, the program defines functions for advanced mathematical operations such as exponentiation, logarithm, and square root.

def add (n1, n2):
return n1 + n2
def subtract (n1, n2):
return n1 - n2
def multiply (n1, n2):
return n1 * n2
def division (n1, n2):
return n1 / n2
def exponent(n1, n2):
return n1 ** n2
def logarithm(n1):
return math.log(n1)
def square_root(n1):
return math.sqrt(n1)

After defining the mathematical functions, the program defines the calculator function where the main calculator code is written. Which will be explain later on this article. After that, the clear variable is defined using lambda function which is used to clear the console. Then the program creates a dictionary that maps each operator to its corresponding function. This allows the user to enter a symbol and the program automatically knows which mathematical function to execute. Then the calculator function is called where the program starts.

clear = lambda: os.system('cls')
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": division,
"exp": exponent,
"log": logarithm,
"sqrt": square_root
}
calculator()

Inside of the calculator() function:

The program starts by clearing the console output and displaying the ASCII art logo. Then, it prompts the user to enter the first number. It uses a while loop to keep running the calculator and prompt the user for a mathematical operation. If the user enters an incorrect operation, the program prints an error message and breaks out of the loop.

def calculator():
clear()
print(art.logo)
num1 = float(input("Enter First Number: "))
    should_run = True    while should_run:
for key in operations:
print(key, end=" ")
chosen_symbol=input("\nChoose an operation from the symbols: ") if chosen_symbol not in operations:
print("You've chosen a wrong operations. Please Try Again!")
break

When the user picks an appropriate operation, the application uses the earlier created dictionary to identify the matching mathematical function. The program immediately runs the advanced mathematical functions like “logarithm”, “exponent” or “square root” using the first integer as an input. The application prompts the user to enter the second number for the basic arithmetic functions like “add”, “subtract”, “multiply” or “division” before executing the function with both numbers as arguments. Then it prints the result.

operation_function = operations[chosen_symbol]

if chosen_symbol in ["log", "sqrt"]:
answer = round(operation_function(n1=num1),2)
print(f"{chosen_symbol} of {num1} is {(answer)}")
else:
num2 = float(input("Enter Next Number: "))
answer = round(operation_function(n1=num1, n2=num2),2)
            print(f"{num1} {chosen_symbol} {num2} = {answer}")

After the execution of the mathematical function, the program shows 3 options for the user. It asks the user to either continue the calculation with the current answer or reset the program to starts form beginning or quit the program. If the user decides to proceed with the calculation, the program saves the result and prompts the user for the next mathematical operation. The application is terminated if the user chooses to discontinue it. And the program starts again if the user choses to reset the values.

user_choice = input("Type 'Y' to continue calculation with the current answer or 'N' to exit or type anything to reset the values - ").lower()

if user_choice == 'y':
num1 = answer
print(f"Current Answer: {answer}")
elif user_choice == 'n':
should_run = False
else:
should_run = False
calculator()

Full Code

Sample Run

Sample Run

Features:

Program’s Features

  • Performs basic arithmetic operations like addition, subtraction, multiplication, and division
  • Includes advanced mathematical functions such as exponentiation, logarithm, and square root
  • Has an intuitive user interface with ASCII art logo and prompt messages

Python Concepts and Techniques Used

  • math and os libraries
  • Basic arithmetic operations
  • if-elif-else statements and while-for loop
  • Combining dictionaries and functions
  • User input and output
  • Function definition and execution

You learned how to make a simple calculator in Python using math operations. You got to know how to create functions for advanced mathematical operations like exponentiation, logarithm, and square root. You can develop your calculator and improve it by adding new features by following the step-by-step code description.

Ready to Level Up? Complete These Challenges

Now that you’ve learned how to create a basic calculator, it’s time to put your skills to the test! Here are some fun challenges to help you take your Python knowledge to the next level. Are you ready to level up? Let’s go!

  1. Add a new function to the calculator that calculates the factorial of a number.
  2. Modify the calculator to handle multiple operations in a single calculation, such as “2 + 3 * 4”.
  3. Implement error handling in the calculator to handle cases where the user enters invalid inputs, such as non-numeric values or division by zero.

Please let me know if you complete these tasks. I’d would like to see them.

This article is a part of my Python Project Journal. To learn more about my journey in learning Python and to see my other projects, check out this project journal. Thank you!

--

--