Skip to content
  • SiteMap
  • Our Services
  • Frequently Asked Questions (FAQ)
  • Support
  • About Us

UpdateGadh

Update Your Skills.

  • Home
  • Projects
    •  Blockchain projects
    • Python Project
    • Data Science
    •  Ai projects
    • Machine Learning
    • PHP Project
    • React Projects
    • Java Project
    • SpringBoot
    • JSP Projects
    • Java Script Projects
    • Code Snippet
    • Free Projects
  • Tutorials
    • Ai
    • Machine Learning
    • Advance Python
    • Advance SQL
    • DBMS Tutorial
    • Data Analyst
    • Deep Learning Tutorial
    • Data Science
    • Nodejs Tutorial
  • Blog
  • Contact us
  • Toggle search form
Basic Calculator in Python with Source Code - Basic Calculator in Python

Basic Calculator in Python with Source Code

Posted on October 14, 2024October 14, 2024 By Rishabh saini No Comments on Basic Calculator in Python with Source Code

Basic Calculator in Python

If you’re new to Python and looking for a fun and simple project to practice your programming skills, building a basic calculator is a perfect choice! It’s a great way to learn core programming concepts like functions, loops, and user input. Plus, you’ll end up with a useful tool that can handle simple arithmetic operations like addition, subtraction, multiplication, and division.

Table of Contents

  • Basic Calculator in Python
  • Features
    • Steps to Build
  • Step 1: Define Functions for Each Operation
    • Explanation:
  • Step 2: Create the User Input System
    • Explanation:
  • Step 3: Add Error Handling and Final Touches
  • Full Source Code for the Basic Calculator
  • How to Run the Calculator Program

Let’s get started!

Features

The Python calculator we’ll build will support the following operations:

  • Addition: Adding two numbers.
  • Subtraction: Subtracting one number from another.
  • Multiplication: Multiplying two numbers.
  • Division:Dividing an integer by another (with zero division mistake handled).

Download New Real Time Projects :-Click here

Steps to Build

Here’s an overview of what we’ll do:

  1. Construct a user input mechanism to gather operators and numbers.
  2. For every arithmetic operation, create a function.
  3. Implement a menu system to guide the user through the operations.
  4. Add error handling to make sure the calculator works smoothly.

Let’s dive into the code!

https://updategadh.com/category/php-project

Step 1: Define Functions for Each Operation

The first thing we’ll do is define separate functions for each of the basic arithmetic operations (addition, subtraction, multiplication, and division). This will make the code more modular and easier to understand.

Here’s the code to define the basic operations:

# Function for addition
def add(x, y):
    return x + y

# Function for subtraction
def subtract(x, y):
    return x - y

# Function for multiplication
def multiply(x, y):
    return x * y

# Function for division
def divide(x, y):
    if y == 0:
        return "Error! Division by zero is not allowed."
    else:
        return x / y

Explanation:

  • We define four separate functions, each taking two parameters (x and y), which represent the two numbers that the user will input.
  • For the division function, we’ve added basic error handling to avoid division by zero.
Beauty Parlour Management

Step 2: Create the User Input System

Next, we’ll create a system that allows the user to input the numbers and choose the operation they want to perform. Python’s input() function will be used to collect user data.

Here’s the code for gathering user input and choosing an operation:

def calculator():
    print("Welcome to the Basic Python Calculator!")

    # Display the available operations
    print("Select operation:")
    print("1. Addition")
    print("2. Subtraction")
    print("3. Multiplication")
    print("4. Division")

    # Take input from the user
    choice = input("Enter choice (1/2/3/4): ")

    if choice in ['1', '2', '3', '4']:
        # Input the numbers
        try:
            num1 = float(input("Enter first number: "))
            num2 = float(input("Enter second number: "))
        except ValueError:
            print("Invalid input! Please enter numeric values.")
            return

        # Perform the chosen operation
        if choice == '1':
            print(f"{num1} + {num2} = {add(num1, num2)}")
        elif choice == '2':
            print(f"{num1} - {num2} = {subtract(num1, num2)}")
        elif choice == '3':
            print(f"{num1} * {num2} = {multiply(num1, num2)}")
        elif choice == '4':
            print(f"{num1} / {num2} = {divide(num1, num2)}")
    else:
        print("Invalid choice! Please select a valid operation.")

# Call the calculator function to run the program
calculator()

Explanation:

  • The program first displays a menu of available operations (Addition, Subtraction, Multiplication, and Division).
  • It then asks the user to select an operation by entering 1, 2, 3, or 4.
  • The program checks whether the user’s input is valid and then prompts the user to input two numbers.
  • Based on the user’s selection, the corresponding function is called, and the result is displayed.

Step 3: Add Error Handling and Final Touches

We’ve already added error handling for invalid numeric inputs and division by zero, but it’s important to ensure the user experience is smooth. Here’s a breakdown of what we added:

  • Handling non-numeric input: If the user enters something that isn’t a number, the program will print an error message and exit gracefully.
  • Handling invalid choices: If the user selects an option outside of the given choices (1, 2, 3, 4), the program will inform them and stop.
  • Handling division by zero: We added an extra check to avoid dividing by zero, which is a common error in calculators.
Basic Calculator in Python with Source Code
Basic Calculator in Python with Source Code
Basic Calculator in Python with Source Code
Basic Calculator in Python with Source Code

Full Source Code for the Basic Calculator

Here’s the full code for the Basic Python Calculator:

# Basic Calculator in Python

# Function for addition
def add(x, y):
    return x + y

# Function for subtraction
def subtract(x, y):
    return x - y

# Function for multiplication
def multiply(x, y):
    return x * y

# Function for division with error handling for division by zero
def divide(x, y):
    if y == 0:
        return "Error! Division by zero is not allowed."
    else:
        return x / y

# Main calculator function
def calculator():
    print("Welcome to the Basic Python Calculator!")

    # Display the available operations
    print("Select operation:")
    print("1. Addition")
    print("2. Subtraction")
    print("3. Multiplication")
    print("4. Division")

    # Take input from the user
    choice = input("Enter choice (1/2/3/4): ")

    if choice in ['1', '2', '3', '4']:
        # Input the numbers
        try:
            num1 = float(input("Enter first number: "))
            num2 = float(input("Enter second number: "))
        except ValueError:
            print("Invalid input! Please enter numeric values.")
            return

        # Perform the chosen operation
        if choice == '1':
            print(f"{num1} + {num2} = {add(num1, num2)}")
        elif choice == '2':
            print(f"{num1} - {num2} = {subtract(num1, num2)}")
        elif choice == '3':
            print(f"{num1} * {num2} = {multiply(num1, num2)}")
        elif choice == '4':
            print(f"{num1} / {num2} = {divide(num1, num2)}")
    else:
        print("Invalid choice! Please select a valid operation.")

# Call the calculator function to run the program
calculator()

How to Run the Calculator Program

  1. Copy the above code and paste it into a Python file (e.g., calculator.py).
  2. Open your terminal or command prompt.
  3. Go to the directory containing your Python file.
  4. Run the script by typing python calculator.py.

You can now perform basic arithmetic operations directly from your terminal!

  • Basic Calculator in Python with Source Code
  • Basic Calculator in Python
Post Views: 870
code Snippets Tags:basic calculator in python, Calculator, calculator in python, calculator using python, calculator using python gui, create calculator in python, create gui calculator in tkinter, how to build a simple calculator in python, how to create scientific calculator in python, Python, python calculator, python gui calculator, python gui calculator source code, python gui calculator tkinter, Python Tutorial, simple calculator in python

Post navigation

Previous Post: Beauty Parlour Management System Web Application
Next Post: Top 10 HTML Project Ideas for Beginners

More Related Articles

DES Encryption Program Code Using Java JFrame DES Encryption Program Code Using Java JFrame code Snippets
Scientific Calculator in Python with Source Code - Scientific Calculator in Python with Source Code Scientific Calculator in Python with Source Code code Snippets
Python Code Snippets for Data Science Projects Python Code Snippets for Data Science Projects code Snippets

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

  1. Supply Chain Management PHP and CSS
  2. Online Shopping System using PHP, MySQL with Free Source Code
  3. F1 Race Road Game in Python Free Source Code
  4. Supplier Management System in Java with Free Code
  5. Create Address Book in Python with Source Code
  6. Contact Management in Python with Source Code

Most Viewed Posts

  1. Top Large Language Models in 2025
  2. Online Shopping System using PHP, MySQL with Free Source Code
  3. login form in php and mysql , Step-by-Step with Free Source Code
  4. Flipkart Clone using PHP And MYSQL Free Source Code
  5. News Portal Project in PHP and MySql Free Source Code
  6. User Login & Registration System Using PHP and MySQL Free Code
  7. Top 10 Final Year Project Ideas in Python
  8. Online Bike Rental Management System Using PHP and MySQL
  9. E learning Website in php with Free source code
  10. E-Commerce Website Project in Java Servlets (JSP)
  • AI
  • ASP.NET
  • Blockchain
  • ChatCPT
  • code Snippets
  • Collage Projects
  • Data Science Project
  • Data Science Tutorial
  • DBMS Tutorial
  • Deep Learning Tutorial
  • Final Year Projects
  • Free Projects
  • How to
  • html
  • Interview Question
  • Java Notes
  • Java Project
  • Java Script Notes
  • JAVASCRIPT
  • Javascript Project
  • JSP JAVA(J2EE)
  • Machine Learning Project
  • Machine Learning Tutorial
  • MySQL Tutorial
  • Node.js Tutorial
  • PHP Project
  • Portfolio
  • Python
  • Python Interview Question
  • Python Projects
  • PythonFreeProject
  • React Free Project
  • React Projects
  • Spring boot
  • SQL Tutorial
  • TOP 10
  • Uncategorized
  • Online Examination System in PHP with Source Code
  • AI Chatbot for College and Hospital
  • Job Portal Web Application in PHP MySQL
  • Online Tutorial Portal Site in PHP MySQL — Full Project with Source Code
  • Online Job Portal System in JSP Servlet MySQL

Most Viewed Posts

  • Top Large Language Models in 2025 (8,614)
  • Online Shopping System using PHP, MySQL with Free Source Code (5,215)
  • login form in php and mysql , Step-by-Step with Free Source Code (4,867)

Copyright © 2026 UpdateGadh.

Powered by PressBook Green WordPress theme