Chapter 8: Simple Calculator Program¶
🚀 Open Notebook¶
📺 Video Tutorial¶
Let’s code a simple python calculator! 🧮 (8:20)
📚 What You’ll Learn¶
Build a functional calculator that performs basic mathematical operations!
🎯 Learning Objectives¶
Combine user input with conditional statements
Create a menu-driven program
Handle different mathematical operations
Validate user input
Build a complete, useful program
📖 Concept Explanation¶
What is a Calculator Program?¶
A calculator program:
Asks the user what operation they want to perform
Gets the numbers to calculate
Performs the requested operation
Displays the result
Program Flow¶
1. Display available operators → 2. Get operator choice → 3. Get numbers →
4. Check operator and calculate → 5. Display result
💡 Complete Program Breakdown¶
Step 1: Get Operator¶
operator = input("Enter operator (+, -, *, /, %): ")
Step 2: Get Numbers¶
number1 = float(input("Enter first number: "))
number2 = float(input("Enter second number: "))
Note: We use float() to handle both whole numbers and decimals
Step 3: Calculate Based on Operator¶
if operator == "+":
result = number1 + number2
elif operator == "-":
result = number1 - number2
# ... and so on
✍️ Practice Exercises¶
Exercise 1: Add Division by Zero Check¶
elif operator == "/":
if number2 == 0:
print("Error: Cannot divide by zero!")
else:
print(f"{number1} / {number2} = {number1 / number2}")
Exercise 2: Add More Operations¶
Add these operators:
**for exponentiation (power)//for floor divisionsqrtfor square root
Exercise 3: Continuous Calculator¶
Make the calculator run in a loop until user chooses to exit:
while True:
# calculator code here
continue_calc = input("Another calculation? (yes/no): ")
if continue_calc.lower() != "yes":
break
Exercise 4: Calculator with Memory¶
Store the last result and allow using it in next calculation:
memory = 0
# Allow user to type "M" to use memory value
🔍 Enhancements¶
Enhancement 1: Better Output Formatting¶
if operator == "+":
result = number1 + number2
print(f"\n{number1} + {number2} = {result}")
print(f"Result: {result:.2f}") # 2 decimal places
Enhancement 2: Input Validation¶
valid_operators = ['+', '-', '*', '/', '%']
if operator not in valid_operators:
print("Invalid operator!")
Enhancement 3: Try-Except for Error Handling¶
try:
number1 = float(input("Enter first number: "))
number2 = float(input("Enter second number: "))
except ValueError:
print("Error: Please enter valid numbers!")
🎮 Advanced Calculator Features¶
Scientific Calculator¶
import math
if operator == "sqrt":
result = math.sqrt(number1)
elif operator == "sin":
result = math.sin(math.radians(number1))
elif operator == "cos":
result = math.cos(math.radians(number1))
Calculator with History¶
history = []
# After each calculation:
history.append(f"{number1} {operator} {number2} = {result}")
# Display history:
for calc in history:
print(calc)
📝 Common Operators Explained¶
Operator |
Name |
Example |
Result |
|---|---|---|---|
|
Addition |
|
|
|
Subtraction |
|
|
|
Multiplication |
|
|
|
Division |
|
|
|
Modulus |
|
|
|
Power |
|
|
|
Floor Division |
|
|
🚀 Challenge Projects¶
Challenge 1: Multi-Step Calculator¶
# Allow: 5 + 3 * 2 - 1
# Parse and calculate following order of operations
Challenge 2: Unit Converter¶
Add conversions:
Temperature (C to F, F to C)
Length (miles to km, km to miles)
Weight (lbs to kg, kg to lbs)
Challenge 3: Percentage Calculator¶
# Calculate:
# - What is X% of Y?
# - X is what % of Y?
# - Percentage increase/decrease
Challenge 4: GUI Calculator¶
Use tkinter to create a calculator with buttons:
import tkinter as tk
# Create calculator with button interface
💻 Complete Enhanced Calculator¶
def calculator():
print("=== Simple Calculator ===")
print("Operations: +, -, *, /, %, **, //")
operator = input("\nEnter operator: ")
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
if num2 == 0:
print("Error: Division by zero!")
return
result = num1 / num2
elif operator == "%":
result = num1 % num2
elif operator == "**":
result = num1 ** num2
elif operator == "//":
result = num1 // num2
else:
print("Invalid operator!")
return
print(f"\n{num1} {operator} {num2} = {result}")
print(f"Result: {result:.2f}")
except ValueError:
print("Error: Please enter valid numbers!")
# Run calculator
calculator()
🔗 Next Chapter¶
Continue to Chapter 9: Weight Converter to build another practical conversion program!