Skip to content

Simple Calculator

Abstract

Creating a simple calculator is a great project for beginners. You will learn how to use functions, return values, and if statements. In this project, you will create a calculator that can add, subtract, multiply, and divide two numbers. You can also calculate the square root of a number and power of a number. This application is a command-line application. You can run this application in the terminal.

Prerequisites

  • Python 3.6 or above
  • Text Editor or IDE

Getting Started

Create a new project

  1. Create a new project folder and name it simple-calculatorsimple-calculator.
  2. Create a new file and name it calculator.pycalculator.py.
  3. Open the project folder in your favorite text editor or IDE.
  4. Open the calculator.pycalculator.py file in your text editor or IDE.

Write the code

  1. Add following code to the calculator.pycalculator.py file.
⚙️ Simple Calculator
Simple Calculator
# Calculator Program
 
# Importing Modules
import math
 
# Defining Functions
def add(x, y):
    return x + y
 
def sub(x, y):
    return x - y
 
def mul(x, y):
    return  x * y
 
def div(x, y):
    return x / y
 
def sqrt(x):
    return math.sqrt(x)
 
def power(x, y):
    return math.pow(x, y)
 
 
# Main Program
print("Select Operation.")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Square Root")
print("6. Power")
print("E. Exit")
print("R. Restart")
 
while True:
    choice = input("Enter Choice (1/2/3/4/5/6/E/R): ")
 
    if choice in ('1', '2', '3', '4', '5', '6'):
        num1 = float(input("Enter First Number: "))
        num2 = float(input("Enter Second Number: "))
 
        if choice == '1':
            print(num1, "+", num2, "=", add(num1, num2))
 
        elif choice == '2':
            print(num1, "-", num2, "=", sub(num1, num2))
 
        elif choice == '3':
            print(num1, "*", num2, "=", mul(num1, num2))
 
        elif choice == '4':
            print(num1, "/", num2, "=", div(num1, num2))
 
        elif choice == '5':
            print("Square Root of", num1, "=", sqrt(num1))
            print("Square Root of", num2, "=", sqrt(num2))
 
        elif choice == '6':
            print(num1, "to the power of", num2, "=", power(num1, num2))
 
    elif choice.upper() == 'E':
        confirm = input("Are you sure you want to exit? (Y/N): ")
        if confirm.upper() == 'Y':
            print("Exiting...")
            break
        elif confirm.upper() == 'N':
            print("Select Operation.")
            print("1. Addition")
            print("2. Subtraction")
            print("3. Multiplication")
            print("4. Division")
            print("5. Square Root")
            print("6. Power")
            print("E. Exit")
            print("R. Restart")
        else:
            print("Invalid Input")
 
    elif choice.upper() == 'R':
        print("Restarting...")
        print("Select Operation.")
        print("1. Addition")
        print("2. Subtraction")
        print("3. Multiplication")
        print("4. Division")
        print("5. Square Root")
        print("6. Power")
        print("E. Exit")
        print("R. Restart")
 
    else:
        print("Invalid Input") 
Simple Calculator
# Calculator Program
 
# Importing Modules
import math
 
# Defining Functions
def add(x, y):
    return x + y
 
def sub(x, y):
    return x - y
 
def mul(x, y):
    return  x * y
 
def div(x, y):
    return x / y
 
def sqrt(x):
    return math.sqrt(x)
 
def power(x, y):
    return math.pow(x, y)
 
 
# Main Program
print("Select Operation.")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Square Root")
print("6. Power")
print("E. Exit")
print("R. Restart")
 
while True:
    choice = input("Enter Choice (1/2/3/4/5/6/E/R): ")
 
    if choice in ('1', '2', '3', '4', '5', '6'):
        num1 = float(input("Enter First Number: "))
        num2 = float(input("Enter Second Number: "))
 
        if choice == '1':
            print(num1, "+", num2, "=", add(num1, num2))
 
        elif choice == '2':
            print(num1, "-", num2, "=", sub(num1, num2))
 
        elif choice == '3':
            print(num1, "*", num2, "=", mul(num1, num2))
 
        elif choice == '4':
            print(num1, "/", num2, "=", div(num1, num2))
 
        elif choice == '5':
            print("Square Root of", num1, "=", sqrt(num1))
            print("Square Root of", num2, "=", sqrt(num2))
 
        elif choice == '6':
            print(num1, "to the power of", num2, "=", power(num1, num2))
 
    elif choice.upper() == 'E':
        confirm = input("Are you sure you want to exit? (Y/N): ")
        if confirm.upper() == 'Y':
            print("Exiting...")
            break
        elif confirm.upper() == 'N':
            print("Select Operation.")
            print("1. Addition")
            print("2. Subtraction")
            print("3. Multiplication")
            print("4. Division")
            print("5. Square Root")
            print("6. Power")
            print("E. Exit")
            print("R. Restart")
        else:
            print("Invalid Input")
 
    elif choice.upper() == 'R':
        print("Restarting...")
        print("Select Operation.")
        print("1. Addition")
        print("2. Subtraction")
        print("3. Multiplication")
        print("4. Division")
        print("5. Square Root")
        print("6. Power")
        print("E. Exit")
        print("R. Restart")
 
    else:
        print("Invalid Input") 
  1. Save the file.
  2. Open the terminal and navigate to the project folder.
  3. Run the following command to run the application.
command
C:\Users\username\Documents\simple-calculator> python calculator.py
Select Operation.
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square Root
6. Power
E. Exit
R. Restart
Enter Choice (1/2/3/4/5/6/E/R): 1
Enter First Number: 2
Enter Second Number: 4
2.0 + 4.0 = 6.0
Enter Choice (1/2/3/4/5/6/E/R): E
Are you sure you want to exit? (Y/N): Y
Exiting...
command
C:\Users\username\Documents\simple-calculator> python calculator.py
Select Operation.
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square Root
6. Power
E. Exit
R. Restart
Enter Choice (1/2/3/4/5/6/E/R): 1
Enter First Number: 2
Enter Second Number: 4
2.0 + 4.0 = 6.0
Enter Choice (1/2/3/4/5/6/E/R): E
Are you sure you want to exit? (Y/N): Y
Exiting...

Explanation

In this application, we create some functions to perform the mathematical operations. We use the mathmath module to calculate the square root and power of a number.

We use the whilewhile loop to run the application until the user exits the application. We use the ifif statement to check the user input and perform the operation accordingly. We use the input()input() function to get the user input. We use the float()float() function to convert the user input to a floating-point number. We use the print()print() function to print the output to the terminal. We use the breakbreak statement to exit the whilewhile loop. We use the upper()upper() function to convert the user input to uppercase. We use the elifelif statement to check multiple conditions. We use the elseelse statement to execute the code if the ifif statement condition is FalseFalse. We use the returnreturn statement to return the value from the function. We use the defdef keyword to define a function. We use the importimport keyword to import the mathmath module. We use the math.sqrt()math.sqrt() function to calculate the square root of a number. We use the math.pow()math.pow() function to calculate the power of a number.

The Usage Guide

  • If you want to perform the addition operation, you can press the 11 key.
  • If you want to perform the subtraction operation, you can press the 22 key.
  • If you want to perform the multiplication operation, you can press the 33 key.
  • If you want to perform the division operation, you can press the 44 key.
  • If you want to calculate the square root of a number, you can press the 55 key.
  • If you want to calculate the power of a number, you can press the 66 key.
  • If you want to exit the application, you can press the EE or ee key.
  • If you want to restart the application, you can press the RR or rr key.

Next Steps

You can add more mathematical operations to this application. You can add the following operations to this application.

  • Factorial
  • Logarithm
  • Trigonometric Functions
  • Exponential Functions
  • Hyperbolic Functions
  • Rounding Functions
  • Summation Functions
  • Product Functions
  • More Mathematical Functions

Congratulations 🎉 you have successfully created a simple calculator in Python. You can find the complete source code of this project on Github

Was this page helpful?

Let us know how we did