Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Simple Calculator in Python
2.1.
Using Conditional Statements
2.2.
Using Conditional Statements and Modular Functions
2.3.
Simple Calculator in Python Using eval()
3.
Example of Simple Calculator in Python:
4.
Frequently Asked Questions
4.1.
Which is a simple calculator?
4.2.
What is a GUI calculator?
4.3.
Is Python a good calculator?
4.4.
How do you make a simple calculator in Python?
4.5.
How do I use Python as a calculator?
4.6.
Simple Calculator in Python Using eval()
4.7.
What is calculator mode in Python?
5.
Conclusion
Last Updated: Aug 28, 2024
Easy

Python Program to Make a Simple Calculator

Introduction

Python is an extremely powerful and versatile language. It has a wide range of functions and applications. Even after this, Python is one of the easiest programming languages to learn. 

Python Program to Make a Simple Calculator

This article will discuss a program to create a simple calculator in Python.

Simple Calculator in Python

Building a simple calculator in Python is a good way to familiarize yourself with some basic Python concepts. While creating a simple calculator in Python, we will use some of the most basic features of Python.

Features such as if-else conditional statements, function calls, and other fundamental elements are used in the program to create a simple calculator in Python.

There are different ways to create a simple calculator in Python. Let us discuss some of them here.

We will create a command line application for a simple calculator in Python rather than a GUI(Graphical User Interface) application.

Using Conditional Statements

We will code for a simple calculator in Python program to create a simple calculator in Python utilizing only if-else conditional statements.

# Program for a Simple Calculator in Python
while True:
    # Options
    print(
        "Enter 1 to ADD Two Numbers:\n"\
        "Enter 2 to SUBTRACT Two Numbers:\n"\
        "Enter 3 to MULTIPLY Two Numbers:\n"\
        "Enter 4 to DIVIDE Two Numbers:\n"\
        "Enter q or Q to Exit")
        
    # Operation to be performed
    operation = input()
    
    # Exit Condition for Calculator
    if operation == 'q'  or operation == 'Q':
        break
        
    # Take the numbers as input
    num_1 = float(input("Enter the First Number: "))
    num_2 = float(input("Enter the Second Number: "))
    operation = int(operation)
    print()
    
    # Addition
    if operation == 1:
        result = num_1+num_2
        print(f"{num_1} + {num_2} = {result}\n")
        
    # Subtraction
    elif operation == 2:
        result = num_1-num_2
        print(f"{num_1} - {num_2} = {result}\n")
        
    # Multiplication
    elif operation == 3:
        result = num_1*num_2
        print(f"{num_1} X {num_2} = {result}\n")
        
    # Division
    elif operation == 4:
        # Division by Zero Error
        if num_2 == 0:
            print("ERROR DIVISION BY ZERO!!!\n")
            continue
        result = num_1/num_2
        print(f"{num_1} / {num_2} = {result}\n")
        
    # Invalid Input
    else:
        print("Enter a Valid Option!!!\n")
You can also try this code with Online Python Compiler
Run Code


Output:

Enter 1 to ADD Two Numbers:
Enter 2 to SUBTRACT Two Numbers:
Enter 3 to MULTIPLY Two Numbers:
Enter 4 to DIVIDE Two Numbers:
Enter q or Q to Exit
1
Enter the First Number: 7
Enter the Second Number: 8
7.0 + 8.0 = 15.0
Enter 1 to ADD Two Numbers:
Enter 2 to SUBTRACT Two Numbers:
Enter 3 to MULTIPLY Two Numbers:
Enter 4 to DIVIDE Two Numbers:
Enter q or Q to Exit

Also see, Nmap commands

Using Conditional Statements and Modular Functions

Instead of directly writing the code for each operation, we can create functions for each operation to make the code more modular.

Here is a flowchart for the simple calculator in Python program we are going to code:

Conditional Statements and Modular Functions

Now, let us take a look at the program.

# Program for a Simple Calculator in Python

# Addition Function
def addition(num_1, num_2):
    return num_1+num_2

# Subtraction Function
def subtraction(num_1, num_2):
    return num_1-num_2

# Multiplication Function
def multiplication(num_1, num_2):
    return num_1*num_2

#Division Function
def division(num_1, num_2):
    return num_1/num_2

while True:
    # Options
    print(
        "Enter 1 to ADD Two Numbers:\n"\
        "Enter 2 to SUBTRACT Two Numbers:\n"\
        "Enter 3 to MULTIPLY Two Numbers:\n"\
        "Enter 4 to DIVIDE Two Numbers:\n"\
        "Enter q or Q to Exit")
        
    # Operation to be performed
    operation = input()
    
    # Exit Condition for Calculator
    if operation == 'q'  or operation == 'Q':
        break
        
    # Take the numbers as input
    num_1 = float(input("Enter the First Number: "))
    num_2 = float(input("Enter the Second Number: "))
    operation = int(operation)
    print()
    
    # Addition
    if operation == 1:
        result = addition(num_1,num_2)
        print(f"{num_1} + {num_2} = {result}\n")
        
    # Subtraction
    elif operation == 2:
        result = subtraction(num_1,num_2)
        print(f"{num_1} - {num_2} = {result}\n")
        
    # Multiplication
    elif operation == 3:
        result = multiplication(num_1,num_2)
        print(f"{num_1} X {num_2} = {result}\n")
        
    # Division
    elif operation == 4:
        # Division by Zero Error
        if num_2 == 0:
            print("ERROR DIVISION BY ZERO!!!\n")
            continue
        result = division(num_1,num_2)
        print(f"{num_1} / {num_2} = {result}\n")
        
    # Invalid Input
    else:
        print("Enter a Valid Option!!!\n")
You can also try this code with Online Python Compiler
Run Code


Output:

Enter 1 to ADD Two numbers:
Enter 2 to SUBTRACT Two Numbers:
Enter 3 to MULTIPLY Two Numbers:
Enter 4 to DIVIDE Two Numbers:
Enter q or Q to Exit: 
2
Enter the First Number: 55
Enter the Second Number: 132
55.0 - 132.0 = -77.0
Enter 1 to ADD Two numbers:
Enter 2 to SUBTRACT Two Numbers:
Enter 3 to MULTIPLY Two Numbers:
Enter 4 to DIVIDE Two Numbers:
Enter q or Q to Exit: 
3
Enter the First Number: 12
Enter the Second Number: 5
12.0 X  5.0= 60.0
Enter 1 to ADD Two numbers:
Enter 2 to SUBTRACT Two Numbers:
Enter 3 to MULTIPLY Two Numbers:
Enter 4 to DIVIDE Two Numbers:
Enter q or Q to Exit:
q

Simple Calculator in Python Using eval()

We have now created a Simple Calculator in Python using basic programming concepts in Python. However, to evaluate more complex expressions, Python also has an inbuilt function called eval()

Mathematical expressions can be passed to this function in the form of a string to obtain results. Expressions consisting of variables (which have been declared before in the program) can also be evaluated using this function. 

This has a rather simple implementation to it as well.

# Simple Calculator in Python
expression = input("Please Enter The Expression to be Evaluated: ")

result = eval(expression)

print(f"The Expression {expression} Gives the Result: {result}")
You can also try this code with Online Python Compiler
Run Code


Output:

Test Case 1:

Input: 12+(2*4/5)

Expected Output: 13.6

Output:

Please Enter The Expression to be Evaluated: 12+(2*4/5)
The Expression12+(2*4/5) Gives the Result:13.6

Test Case 2:

Input: 14/(12/6 - 2)

Expected Output: 

Since the expression (12/6-2) results in a 0, the program should give a zero division error.

Output:

Please Enter The Expression to be Evaluated: 14/(12/6 - 2)
Traceback (most recent call last):
 File "<string>", line 4, in <module>
 File "<string>", line 1, in <module>
ZeroDivisionError: float division by zero

You can try it on online python compiler.

Example of Simple Calculator in Python:

Here's an example code for a simple calculator in Python:
 

# Define a function to perform the calculations
def calculate(num1, num2, operator):
   if operator == '+':
       return num1 + num2
   elif operator == '-':
       return num1 - num2
   elif operator == '*':
       return num1 * num2
   elif operator == '/':
       if num2 == 0:
           return "Cannot divide by zero"
       else:
           return num1 / num2
   else:
       return "Invalid operator"
# Prompt the user for input
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
operator = input("Enter the operator (+, -, *, /): ")
# Call the calculate function and print the result
result = calculate(num1, num2, operator)
print("Result: ", result)

This code defines a function calculate that takes in two numbers and an operator, and performs the corresponding arithmetic operation. It also includes error handling for dividing by zero. The code prompts the user for input, calls the calculate function, and prints the result.

Check out this article - Quicksort Python, Swapcase in Python

Frequently Asked Questions

Which is a simple calculator?

A simple calculator is a device or software application that is used to perform basic arithmetic operations like addition, subtraction, multiplication, and division. It is usually designed to be user-friendly and easy to operate.

What is a GUI calculator?

A GUI calculator, or Graphical User Interface calculator, is a software application that provides a user-friendly visual interface for performing mathematical calculations, often including advanced functions and features.

Is Python a good calculator?

Yes, Python is a versatile and capable calculator. Its simplicity, extensive math libraries, and ease of use make it suitable for a wide range of mathematical calculations.

How do you make a simple calculator in Python?

To make a simple calculator in Python, you can use the following code:

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operator = input("Enter operator (+, -, *, /): ")
if operator == '+':
   print(num1 + num2)
elif operator == '-':
   print(num1 - num2)
elif operator == '*':
   print(num1 * num2)
elif operator == '/':
   print(num1 / num2)
else:
   print("Invalid operator")

This code prompts the user to enter two numbers and an operator (+, -, *, /). Based on the operator, it performs the corresponding arithmetic operation and prints the result.

How do I use Python as a calculator?

You can use Python as a calculator by opening a Python interpreter or writing scripts to perform mathematical operations like addition, subtraction, multiplication, and division.

Simple Calculator in Python Using eval()

To input a calculator into Python, you can write code that prompts the user for two numbers and an operator, performs the corresponding arithmetic operation using built-in functions, and prints the result.

What is calculator mode in Python?

"Calculator mode" in Python generally refers to a program or code that is designed to perform basic arithmetic operations like addition, subtraction, multiplication, and division and often includes a user interface for inputting numbers and operators.

Conclusion

In this article, we discussed a Python program to create a Simple Calculator in Python. We discussed a few different methods along with the inbuilt eval() function in Python.

Recommended Reading:

You can also consider our paid courses such as DSA in Python to give your career an edge over others!

Live masterclass