Programming isn't just about memorizing syntaxโit's about developing a systematic way of thinking that breaks down complex problems into manageable pieces. This comprehensive guide takes you through 19 carefully crafted scenarios that demonstrate the complete thought process behind writing Python code. You'll learn to ask the right questions, deconstruct problems systematically, plan before coding, and improve iteratively. By the end, you'll think like a programmer, not just write like one.
These first three scenarios will take you step-by-step through the complete thinking process. You'll see exactly how a programmer approaches a problem from the very first question to the final optimized solution.
Problem Statement: "Write a program that asks a user for their age and tells them if they are a child (0-12), teenager (13-19), adult (20-59), or senior (60+)."
try:
age = int(input("Enter your age: "))
if age < 0:
print("Invalid age! Age cannot be negative.")
elif age <= 12:
print("You are a child.")
elif age <= 19:
print("You are a teenager.")
elif age <= 59:
print("You are an adult.")
else:
print("You are a senior.")
except ValueError:
print("Please enter a valid number.")
Key Learning: Always validate user input! The `try-except` pattern is essential for robust programs. Notice how we check the most restrictive conditions first (negative age) before moving to general categories.
Problem Statement: "Create a program that calculates the average of three test scores and assigns a letter grade (A: 90+, B: 80-89, C: 70-79, D: 60-69, F: below 60)."
try:
score1 = float(input("Enter first test score: "))
score2 = float(input("Enter second test score: "))
score3 = float(input("Enter third test score: "))
if 0 <= score1 <= 100 and 0 <= score2 <= 100 and 0 <= score3 <= 100:
average = (score1 + score2 + score3) / 3
if average >= 90:
grade = "A"
elif average >= 80:
grade = "B"
elif average >= 70:
grade = "C"
elif average >= 60:
grade = "D"
else:
grade = "F"
print(f"Average: {average:.1f}, Grade: {grade}")
else:
print("All scores must be between 0 and 100.")
except ValueError:
print("Please enter valid numbers for all scores.")
Key Learning: Notice the compound condition with `and` operators to validate all scores at once. The descending grade check (90, 80, 70, 60) is more intuitive than ascending because we think "A is 90 or above" naturally.
Problem Statement: "Write a program that checks if a password is strong. A strong password must be at least 8 characters long, contain at least one uppercase letter, one lowercase letter, one digit, and one special character."
password = input("Enter your password: ")
special_chars = "!@#$%^&*()_+-=[]{}|;:,.<>?"
# Check all requirements
has_length = len(password) >= 8
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
has_special = any(c in special_chars for c in password)
if has_length and has_upper and has_lower and has_digit and has_special:
print("Strong password! โ")
else:
print("Weak password. Missing:")
if not has_length: print(" - At least 8 characters")
if not has_upper: print(" - Uppercase letter")
if not has_lower: print(" - Lowercase letter")
if not has_digit: print(" - Number")
if not has_special: print(" - Special character")
Key Learning: The `any()` function with generator expressions is a powerful Python pattern. Notice how we store boolean results in descriptive variablesโthis makes the final condition read like English: "if has_length and has_upper and..."
The next 9 scenarios focus on practical coding with interactive explanations. Hover over highlighted code terms to understand the syntax and design decisions behind each choice.
Challenge: Create a game where the computer picks a random number (1-100) and the user has to guess it. Provide hints like "too high" or "too low".
import random
target = random.randint(1, 100)
attempts = 0
max_attempts = 7
print("I'm thinking of a number between 1 and 100!")
print(f"You have {max_attempts} attempts to guess it.")
while attempts < max_attempts:
try:
guess = int(input(f"Attempt {attempts + 1}: Enter your guess: "))
attempts += 1
if guess == target:
print(f"๐ Congratulations! You guessed it in {attempts} attempts!")
break
elif guess < target:
print("๐ Too low! Try a higher number.")
else:
print("๐ Too high! Try a lower number.")
if attempts == max_attempts:
print(f"๐ Game over! The number was {target}.")
except ValueError:
print("Please enter a valid number!")
This introduces key game programming concepts: random number generation, game loops, attempt tracking, and user feedback. The emojis make feedback more engaging!
Challenge: Build a simple shopping cart that lets users add items with prices, calculates subtotal, applies tax (8%), and shows the final total.
cart = []
tax_rate = 0.08
print("๐ Welcome to the Shopping Cart Calculator!")
print("Enter items and prices (type 'done' when finished)")
while True:
item_name = input("Item name: ")
if item_name.lower() == 'done':
break
try:
price = float(input(f"Price for {item_name}: $"))
cart.append({'name': item_name, 'price': price})
print(f"โ Added {item_name} for ${price:.2f}")
except ValueError:
print("Invalid price! Please enter a number.")
if cart:
subtotal = sum(item['price'] for item in cart)
tax = subtotal * tax_rate
total = subtotal + tax
print("\n๐งพ Receipt:")
for item in cart:
print(f" {item['name']}: ${item['price']:.2f}")
print(f"\nSubtotal: ${subtotal:.2f}")
print(f"Tax (8%): ${tax:.2f}")
print(f"Total: ${total:.2f}")
else:
print("No items in cart!")
This scenario introduces lists, dictionaries, and the powerful `sum()` function with generator expressions. Notice how we store structured data (name + price) using dictionaries.
Challenge: Count how many times each word appears in a sentence, ignoring case and punctuation.
import string
text = input("Enter a sentence: ")
# Clean and prepare text
cleaned_text = text.lower().translate(str.maketrans('', '', string.punctuation))
words = cleaned_text.split()
# Count word frequencies
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
# Display results
print("\n๐ Word Frequency:")
for word, count in word_count.items():
print(f" '{word}': {count}")
Challenge: Create a to-do list where users can add tasks, mark them as complete, and view all tasks with their status.
tasks = []
def display_menu():
print("\n๐ To-Do List Manager")
print("1. Add task")
print("2. Mark task complete")
print("3. View all tasks")
print("4. Exit")
while True:
display_menu()
choice = input("Choose an option: ")
if choice == '1':
task = input("Enter new task: ")
tasks.append({'task': task, 'completed': False})
print(f"โ Added: {task}")
elif choice == '2':
if tasks:
for i, task_dict in enumerate(tasks, 1):
status = "โ" if task_dict['completed'] else "โ"
print(f" {i}. {status} {task_dict['task']}")
try:
task_num = int(input("Enter task number to complete: ")) - 1
tasks[task_num]['completed'] = True
print("โ Task marked as complete!")
except (IndexError, ValueError):
print("Invalid task number!")
else:
print("No tasks available!")
elif choice == '3':
if tasks:
print("\n๐ All Tasks:")
for i, task_dict in enumerate(tasks, 1):
status = "โ" if task_dict['completed'] else "โ"
print(f" {i}. {status} {task_dict['task']}")
else:
print("No tasks yet!")
elif choice == '4':
print("๐ Goodbye!")
break
else:
print("Invalid option! Please try again.")
This introduces menu-driven programs, functions for code organization, and the powerful `enumerate()` function for getting both index and value in loops.
Challenge: Convert temperatures between Celsius, Fahrenheit, and Kelvin with input validation and formatted output.
def celsius_to_fahrenheit(celsius):
return (celsius * 9 / 5) + 32
def celsius_to_kelvin(celsius):
return celsius + 273.15
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9
print("๐ก๏ธ Temperature Converter")
print("1. Celsius to Fahrenheit & Kelvin")
print("2. Fahrenheit to Celsius & Kelvin")
print("3. Kelvin to Celsius & Fahrenheit")
try:
choice = int(input("Choose conversion type: "))
temperature = float(input("Enter temperature: "))
if choice == 1:
if temperature < -273.15:
print("Error: Temperature below absolute zero!")
else:
fahrenheit = celsius_to_fahrenheit(temperature)
kelvin = celsius_to_kelvin(temperature)
print(f"{temperature}ยฐC = {fahrenheit:.1f}ยฐF = {kelvin:.1f}K")
elif choice == 2:
if temperature < -459.67:
print("Error: Temperature below absolute zero!")
else:
celsius = fahrenheit_to_celsius(temperature)
kelvin = celsius_to_kelvin(celsius)
print(f"{temperature}ยฐF = {celsius:.1f}ยฐC = {kelvin:.1f}K")
elif choice == 3:
if temperature < 0:
print("Error: Kelvin cannot be negative!")
else:
celsius = temperature - 273.15
fahrenheit = celsius_to_fahrenheit(celsius)
print(f"{temperature}K = {celsius:.1f}ยฐC = {fahrenheit:.1f}ยฐF")
else:
print("Invalid choice!")
except ValueError:
print("Please enter valid numbers!")
This demonstrates modular programming with functions, mathematical conversions, and domain-specific validation (absolute zero checks for different temperature scales).
Challenge: Analyze a text input to count characters, words, sentences, and find the longest word.
text = input("Enter some text to analyze: ")
# Basic counts
char_count = len(text)
char_no_spaces = len(text.replace(' ', ''))
words = text.split()
word_count = len(words)
# Sentence count (rough estimate)
sentence_endings = ['.', '!', '?']
sentence_count = sum(text.count(ending) for ending in sentence_endings)
# Find longest word
if words:
longest_word = max(words, key=len)
avg_word_length = sum(len(word) for word in words) / word_count
else:
longest_word = "None"
avg_word_length = 0
# Vowel and consonant count
vowels = "aeiouAEIOU"
vowel_count = sum(1 for char in text if char in vowels)
consonant_count = sum(1 for char in text if char.isalpha() and char not in vowels)
# Display results
print("\n๐ Text Analysis Results:")
print("=" * 30)
print(f"Total characters: {char_count}")
print(f"Characters (no spaces): {char_no_spaces}")
print(f"Word count: {word_count}")
print(f"Estimated sentences: {sentence_count}")
print(f"Longest word: '{longest_word}' ({len(longest_word)} chars)")
print(f"Average word length: {avg_word_length:.1f}")
print(f"Vowels: {vowel_count}, Consonants: {consonant_count}")
This showcases advanced string methods, the `max()` function with key parameter, generator expressions, and statistical calculations. Notice the elegant use of `sum()` with generators!
Challenge: Create a bank account system with deposit, withdraw, balance check, and transaction history features.
balance = 1000.00 # Starting balance
transactions = []
def add_transaction(transaction_type, amount):
import datetime
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
transactions.append({
'type': transaction_type,
'amount': amount,
'timestamp': timestamp,
'balance_after': balance
})
print("๐ฆ Welcome to Simple Bank!")
while True:
print("\n1. Check Balance")
print("2. Deposit Money")
print("3. Withdraw Money")
print("4. Transaction History")
print("5. Exit")
choice = input("Choose an option: ")
if choice == '1':
print(f"๐ฐ Current Balance: ${balance:.2f}")
elif choice == '2':
try:
amount = float(input("Enter deposit amount: $"))
if amount > 0:
balance += amount
add_transaction("Deposit", amount)
print(f"โ
Deposited ${amount:.2f}. New balance: ${balance:.2f}")
else:
print("โ ๏ธ Deposit amount must be positive!")
except ValueError:
print("Invalid amount!")
elif choice == '3':
try:
amount = float(input("Enter withdrawal amount: $"))
if amount > 0:
if amount <= balance:
balance -= amount
add_transaction("Withdrawal", amount)
print(f"โ
Withdrew ${amount:.2f}. New balance: ${balance:.2f}")
else:
print("โ Insufficient funds!")
else:
print("โ ๏ธ Withdrawal amount must be positive!")
except ValueError:
print("Invalid amount!")
elif choice == '4':
if transactions:
print("\n๐ Transaction History:")
for transaction in transactions[-10:]: # Last 10 transactions
print(f" {transaction['timestamp']} | {transaction['type']}: ${transaction['amount']:.2f} | Balance: ${transaction['balance_after']:.2f}")
else:
print("No transactions yet!")
elif choice == '5':
print("๐ Thank you for banking with us!")
break
else:
print("Invalid option!")
This demonstrates persistent state management, timestamp handling with datetime module, transaction logging, and defensive programming with balance validation.
Challenge: Build a calculator that performs basic operations and keeps a history of calculations.
Includes operation validation, calculation history, and error handling for division by zero.
Challenge: Manage multiple students and their grades with statistical analysis.
Complex data structures with nested dictionaries and statistical calculations.
Understanding common mistakes is crucial for becoming a better programmer. These 7 scenarios show what happens when code goes wrong and how to fix it.
The Problem: A variation of our age classifier that crashes with invalid input.
age = int(input("Enter your age: ")) # Crashes on non-numbers
if age <= 12:
print("Child")
elif age <= 19:
print("Teenager")
# What about negative ages? Program doesn't check!
Problems identified: No input validation, no error handling, missing edge cases. Solution: Always wrap user input in try-except blocks and validate ranges.
count = 0
while count < 10:
print("Counting...")
# Forgot to increment count!
print("Done") # This line never runs
Always ensure your loop variable changes inside the loop. Consider using `for` loops when you know the exact number of iterations.
Scenario | What Goes Wrong | Why It Happens | Quick Fix |
---|---|---|---|
F3: List Index Chaos | IndexError: list index out of range | Accessing list[5] when list only has 3 items | Check len(list) or use try-except |
F4: Dictionary Key Missing | KeyError: 'name' | Accessing dict['name'] when key doesn't exist | Use dict.get('name', 'default') |
F5: Function Return Confusion | Function returns None instead of value | Forgetting to include return statement | Always return what you calculate |
F6: Variable Scope Mystery | UnboundLocalError or unexpected values | Using variables outside their scope | Understand local vs global scope |
F7: Type Mixing Mayhem | TypeError: unsupported operand types | Trying to add string + integer | Convert types explicitly |
Now it's your turn! These exercises will test everything you've learned. Start with the easier ones and work your way up.