🐍 Lesson 42: Calculator App (Python Project)
1. Project Overview
In short → A calculator app is one of the easiest projects for Python beginners, handling basic addition, subtraction, multiplication, division arithmetic operations.
In detail → A calculator app is a beginner-friendly project that performs basic arithmetic operations like addition, subtraction, multiplication, and division.
2. Why Build a Calculator App?
- You get to practice Python functions, loops, and conditionals
- You learn how to handle user input
- You get to try out error handling (for example, division by zero)
3. Summary
✅ Calculator app = beginner-friendly project
✅ CLI version → practice with functions, loops, conditionals
✅ GUI version → an interactive app built with Tkinter
✅ Error handling → division by zero, invalid input
python
# ===== 1. Basic Calculator Functions =====
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error! Division by zero."
return a / b
# ===== 2. Calculator Loop =====
print("===== Simple Calculator =====")
print("Operations: +, -, *, /")
print("Enter 'q' to quit\n")
while True:
choice = input("Enter operation (+, -, *, /) or 'q' to quit: ")
if choice == 'q':
break
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '+':
print(f"Result: {add(num1, num2)}\n")
elif choice == '-':
print(f"Result: {subtract(num1, num2)}\n")
elif choice == '*':
print(f"Result: {multiply(num1, num2)}\n")
elif choice == '/':
result = divide(num1, num2)
print(f"Result: {result}\n")
else:
print("Invalid operation\n")
except ValueError:
print("Invalid input! Please enter numbers.\n")
# ===== 3. Example Usage =====
print(f"\n===== Example Calculations =====")
print(f"5 + 3 = {add(5, 3)}")
print(f"10 - 4 = {subtract(10, 4)}")
print(f"6 * 7 = {multiply(6, 7)}")
print(f"15 / 3 = {divide(15, 3)}")
print(f"10 / 0 = {divide(10, 0)}")You should see
===== Simple Calculator ===== Operations: +, -, *, / Enter 'q' to quit ===== Example Calculations ===== 5 + 3 = 8 10 - 4 = 6 6 * 7 = 42 15 / 3 = 5.0 10 / 0 = Error! Division by zero.