Module: Mini Projects

Calculator

# Simple Calculator in Python

This project demonstrates a basic calculator that can perform addition, subtraction, multiplication, and division.

## Code

```python
def add(x, y):
  """Adds two numbers."""
  return x + y

def subtract(x, y):
  """Subtracts two numbers."""
  return x - y

def multiply(x, y):
  """Multiplies two numbers."""
  return x * y

def divide(x, y):
  """Divides two numbers. Handles division by zero."""
  if y == 0:
    return "Error! Division by zero."
  else:
    return x / y

# Main program loop
while True:
  print("\nSelect operation:")
  print("1. Add")
  print("2. Subtract")
  print("3. Multiply")
  print("4. Divide")
  print("5. Exit")

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

  if choice in ('1', '2', '3', '4'):
    try:
      num1 = float(input("Enter first number: "))
      num2 = float(input("Enter second number: "))
    except ValueError:
      print("Invalid input. Please enter numbers only.")
      continue  # Go back to the beginning of the loop

    if choice == '1':
      print(num1, "+", num2, "=", add(num1, num2))

    elif choice == '2':
      print(num1, "-", num2, "=", subtract(num1, num2))

    elif choice == '3':
      print(num1, "*", num2, "=", multiply(num1, num2))

    elif choice == '4':
      print(num1, "/", num2, "=", divide(num1, num2))

  elif choice == '5':
    print("Exiting calculator...")
    break  # Exit the loop

  else:
    print("Invalid input. Please enter a valid choice (1/2/3/4/5).")

Explanation

  1. Functions for Operations:

    • add(x, y): Takes two numbers as input and returns their sum.
    • subtract(x, y): Takes two numbers as input and returns their difference.
    • multiply(x, y): Takes two numbers as input and returns their product.
    • divide(x, y): Takes two numbers as input and returns their quotient. It includes error handling to prevent division by zero. If y is 0, it returns an error message.
  2. Main Program Loop:

    • while True:: Creates an infinite loop that continues until the user chooses to exit.
    • Menu: Prints a menu of available operations to the console.
    • User Input: Prompts the user to enter their choice (1-5).
    • Conditional Execution:
      • if choice in ('1', '2', '3', '4'):: Checks if the user's choice is a valid operation (add, subtract, multiply, or divide).
      • Input Validation (try-except): Uses a try-except block to handle potential ValueError exceptions that might occur if the user enters non-numeric input. If a ValueError occurs, it prints an error message and uses continue to restart the loop.
      • Operation Execution: Based on the user's choice, it calls the appropriate function (add, subtract, multiply, or divide) with the two numbers entered by the user. The result is then printed to the console.
      • elif choice == '5':: Checks if the user wants to exit the calculator. If so, it prints an exit message and uses break to terminate the loop.
      • else:: Handles invalid input (choices other than 1-5). It prints an error message.

How to Run

  1. Save the code: Save the code above as a .py file (e.g., calculator.py).
  2. Open a terminal or command prompt: Navigate to the directory where you saved the file.
  3. Run the script: Execute the script using the command python calculator.py.

Features

  • Basic Arithmetic Operations: Performs addition, subtraction, multiplication, and division.
  • Error Handling: Handles division by zero and invalid input.
  • User-Friendly Interface: Provides a simple menu-driven interface.
  • Looping: Allows the user to perform multiple calculations without restarting the program.

Possible Enhancements

  • More Operations: Add more mathematical operations (e.g., exponentiation, square root, modulus).
  • GUI: Create a graphical user interface (GUI) using libraries like Tkinter, PyQt, or Kivy.
  • History: Store a history of calculations.
  • Memory: Implement a memory function to store and recall values.
  • Input Validation: More robust input validation to handle different types of invalid input.
  • Scientific Notation: Support for scientific notation.
  • Unit Conversion: Add unit conversion capabilities.