Skip to main content

How to Build a Basic Calculator in Python

How to Build a Basic Calculator in Python | Rustcode

How to Build a Basic Calculator in Python

Building a basic calculator is a great way to learn Python fundamentals such as user input, conditionals, arithmetic operations, and functions. In this article, you'll learn how to create a simple calculator in Python, step by step, with code examples, outputs, and clear explanations.


What is a Basic Calculator?

  • Definition: A basic calculator performs arithmetic operations like addition, subtraction, multiplication, and division.
  • Use Cases: Quick calculations, learning programming logic, and building blocks for more complex applications.
  • Benefits: Reinforces core Python concepts such as input, output, functions, and error handling.

01. Basic Calculator with User Input

This example takes two numbers and an operator from the user, then performs the calculation.

num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))

if operator == '+':
    result = num1 + num2
elif operator == '-':
    result = num1 - num2
elif operator == '*':
    result = num1 * num2
elif operator == '/':
    result = num1 / num2
else:
    result = "Invalid operator"

print("Result:", result)

Output (example):

Enter first number: 8
Enter operator (+, -, *, /): *
Enter second number: 3
Result: 24.0
Explanation:
  • Uses input() to get numbers and operator from the user.
  • Performs the operation based on the user's input.
  • Handles four basic operations: addition, subtraction, multiplication, and division.
  • Displays the result or an error message for invalid operators.

02. Calculator Using Functions

Defining separate functions for each operation makes the code modular and reusable.

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    return x / y

# Example usage
print("Select operation: +, -, *, /")
op = input("Operator: ")
a = float(input("First number: "))
b = float(input("Second number: "))

if op == '+':
    print("Result:", add(a, b))
elif op == '-':
    print("Result:", subtract(a, b))
elif op == '*':
    print("Result:", multiply(a, b))
elif op == '/':
    print("Result:", divide(a, b))
else:
    print("Invalid operator")

Output (example):

Select operation: +, -, *, /
Operator: -
First number: 10
Second number: 4
Result: 6.0
Explanation:
  • Each arithmetic operation is defined as a function.
  • User selects the operator and inputs two numbers.
  • Makes the code easy to extend and maintain.

03. Handling Invalid Input (Try-Except)

It's important to handle invalid inputs and division by zero errors gracefully.

try:
    a = float(input("Enter first number: "))
    b = float(input("Enter second number: "))
    op = input("Enter operator (+, -, *, /): ")
    if op == '+':
        print("Result:", a + b)
    elif op == '-':
        print("Result:", a - b)
    elif op == '*':
        print("Result:", a * b)
    elif op == '/':
        print("Result:", a / b)
    else:
        print("Invalid operator")
except ValueError:
    print("Invalid input! Please enter numeric values.")
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")

Output (example):

Enter first number: 5
Enter second number: 0
Enter operator (+, -, *, /): /
Error: Division by zero is not allowed.
Explanation:
  • Uses try-except to catch invalid input and division by zero errors.
  • Improves user experience by providing clear error messages.
  • Prevents the program from crashing on bad input.

04. Calculator Using if-elif-else (Menu Driven)

A menu-driven calculator lets users choose operations in a more interactive way.

print("Simple Calculator")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

choice = input("Enter choice (1/2/3/4): ")

a = float(input("First number: "))
b = float(input("Second number: "))

if choice == '1':
    print("Result:", a + b)
elif choice == '2':
    print("Result:", a - b)
elif choice == '3':
    print("Result:", a * b)
elif choice == '4':
    print("Result:", a / b)
else:
    print("Invalid choice")

Output (example):

Simple Calculator
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 3
First number: 6
Second number: 7
Result: 42.0
Explanation:
  • Presents a simple menu for operation selection.
  • Uses if-elif-else to determine which operation to perform.
  • Easy for beginners to understand and use.

05. Comparing Calculator Methods in Python

Method Input Handling Error Handling Extensibility Notes
Basic Input Manual No Low Quick and simple
Functions Manual No High Modular and reusable
Try-Except Manual Yes Medium Handles errors gracefully
Menu Driven Menu No Medium User-friendly interface

Conclusion

Building a basic calculator in Python is an excellent project for beginners to practice user input, conditionals, functions, and error handling. You can start with a simple version and gradually add more features like advanced operations, error checking, or a graphical interface. Mastering these basics will prepare you for more complex Python projects.

Tip: Always validate user input and handle errors gracefully for a better user experience!

Comments