Simple Calculator Implementation in Python
The following code demonstrates a basic calculator that can perform addition, subtraction, multiplication, and division between two numbers.
Example 1: Basic Calculator
# Define functions def add(x, y): """Addition""" return x + y def subtract(x, y): """Subtraction""" return x - y def multiply(x, y): """Multiplication""" return x * y def divide(x, y): """Division""" return x / y # User input print("Select operation:") print("1. Addition") print("2. Subtraction") print("3. Multiplication") print("4. Division") choice = input("Enter your choice (1/2/3/4):") num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) 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 input")
Example Output:
Select operation: 1. Addition 2. Subtraction 3. Multiplication 4. Division Enter your choice (1/2/3/4): 2 Enter the first number: 5 Enter the second number: 2 5 - 2 = 3
Example 2: Calculator with a Loop
The following code expands the calculator to run continuously until the user chooses to exit.
# Simple Calculator Program # Define function for addition def add(x, y): return x + y # Define function for subtraction def subtract(x, y): return x - y # Define function for multiplication def multiply(x, y): return x * y # Define function for division def divide(x, y): if y != 0: return x / y else: return "Cannot divide by zero" # Main program loop while True: print("\nSelect an operation:") print("1. Addition") print("2. Subtraction") print("3. Multiplication") print("4. Division") print("5. Exit") choice = input("Enter the choice number: ") if choice in ('1', '2', '3', '4'): num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) if choice == '1': print(f"Result: {add(num1, num2)}") elif choice == '2': print(f"Result: {subtract(num1, num2)}") elif choice == '3': print(f"Result: {multiply(num1, num2)}") elif choice == '4': print(f"Result: {divide(num1, num2)}") elif choice == '5': print("Exiting the program.") break else: print("Invalid option, please try again.")
Example Output:
Select an operation: 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Exit Enter the choice number: 4 Enter the first number: 10 Enter the second number: 2 Result: 5.0
This implementation offers a continuous loop that enables the user to perform multiple calculations until they choose to exit the program.