Easy Level - Complete Solutions#
This notebook contains solutions to all exercises from the Easy level lessons.
How to Use This Notebook#
Try the exercise first in the original lesson notebook
Come here only after attempting the problem yourself
Compare your solution - there are often multiple correct approaches
Learn from differences - understand why each approach works
Contents#
01 - Introduction to Python#
Solutions for exercises from 01_introduction_to_python.ipynb
Exercise 1: Personal Introduction#
Task: Create a program that prints your name, age, and favorite hobby.
# Solution 1: Simple approach
print("My name is Alice")
print("I am 15 years old")
print("My favorite hobby is reading")
# Solution 2: Using f-strings (more advanced)
name = "Alice"
age = 15
hobby = "reading"
print(f"My name is {name}")
print(f"I am {age} years old")
print(f"My favorite hobby is {hobby}")
Exercise 2: Math Display#
Task: Print calculations: 15 + 27, 100 - 43, 7 * 8, 144 / 12
# Solution 1: Direct printing
print("15 + 27 =", 15 + 27)
print("100 - 43 =", 100 - 43)
print("7 * 8 =", 7 * 8)
print("144 / 12 =", 144 / 12)
# Solution 2: With better formatting
print(f"15 + 27 = {15 + 27}")
print(f"100 - 43 = {100 - 43}")
print(f"7 * 8 = {7 * 8}")
print(f"144 / 12 = {144 / 12}")
Exercise 3: Create ASCII Art#
Task: Create simple ASCII art (house, smiley face, or tree)
# Solution 1: House
print(" /\\ ")
print(" / \\ ")
print(" /____\\ ")
print(" | | ")
print(" | | ")
print(" |____| ")
print() # Empty line
# Solution 2: Smiley Face
print(" **** ")
print(" * * ")
print("* o o *")
print("* <> *")
print(" * \_/ * ")
print(" **** ")
print() # Empty line
# Solution 3: Christmas Tree
print(" * ")
print(" *** ")
print(" ***** ")
print(" ******* ")
print("*********")
print(" ||| ")
print(" ||| ")
Exercise 4: Story Printer#
Task: Write a short 5-line story using print statements
# Example Solution: A Short Adventure
print("Once upon a time, in a land far away...")
print("A young programmer discovered the power of Python.")
print("With each line of code, magical things happened on screen!")
print("The programs grew smarter, solving problems big and small.")
print("And that's how a new coding adventure began!")
# Your story will be different and that's great!
# The important thing is using print() correctly.
Exercise 5: Pattern Challenge#
Task: Print this pattern:
*
**
***
****
*****
# Solution 1: Direct approach
print("*")
print("**")
print("***")
print("****")
print("*****")
print() # Empty line
# Solution 2: Using string multiplication
print("*" * 1)
print("*" * 2)
print("*" * 3)
print("*" * 4)
print("*" * 5)
print() # Empty line
# Solution 3: Using a loop (advanced for this level, but good to see)
for i in range(1, 6):
print("*" * i)
02 - Variables and Data Types#
Solutions for exercises from 02_variables_and_data_types.ipynb
Exercise 1: Personal Profile#
Task: Create variables for your name, age, height, and is_student, then print them.
# Solution
name = "Alice Johnson"
age = 15
height = 5.6 # in feet
is_student = True
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Height: {height} feet")
print(f"Student: {is_student}")
# Verify types
print(f"\nType of name: {type(name)}")
print(f"Type of age: {type(age)}")
print(f"Type of height: {type(height)}")
print(f"Type of is_student: {type(is_student)}")
Exercise 2: Favorite Book#
Task: Create variables for title, author, pages, and rating, then print them.
# Solution
title = "Harry Potter and the Sorcerer's Stone"
author = "J.K. Rowling"
pages = 309
rating = 4.8
print(f"Title: {title}")
print(f"Author: {author}")
print(f"Pages: {pages}")
print(f"Rating: {rating}/5.0")
# Alternative: Create a formatted display
print("\n" + "="*40)
print(f"Book: {title}")
print(f"By: {author}")
print(f"Length: {pages} pages")
print(f"Rating: {'⭐' * int(rating)} ({rating}/5.0)")
print("="*40)
Exercise 3: Type Conversions#
Task: Convert string “100” to int, multiply by 2, convert back to string, and add “0”
# Solution
# Step 1: Create string
num_string = "100"
print(f"Original string: {num_string}, type: {type(num_string)}")
# Step 2: Convert to integer
num_int = int(num_string)
print(f"As integer: {num_int}, type: {type(num_int)}")
# Step 3: Multiply by 2
result = num_int * 2
print(f"After multiplying by 2: {result}")
# Step 4: Convert back to string
result_string = str(result)
print(f"Back to string: {result_string}, type: {type(result_string)}")
# Step 5: Add "0" (string concatenation)
final = result_string + "0"
print(f"After adding '0': {final}")
# All in one line (advanced)
final_oneline = str(int("100") * 2) + "0"
print(f"\nOne-liner result: {final_oneline}")
Exercise 4: Temperature Converter#
Task: Convert temperature from Fahrenheit to Celsius
# Solution
fahrenheit = 72.5
# Formula: (F - 32) * 5/9
celsius = (fahrenheit - 32) * 5/9
print(f"{fahrenheit}°F = {celsius:.2f}°C")
# Test with other temperatures
test_temps = [32, 98.6, 212, 0, -40]
print("\nMore conversions:")
for temp_f in test_temps:
temp_c = (temp_f - 32) * 5/9
print(f"{temp_f}°F = {temp_c:.2f}°C")
Exercise 5: Variable Swap#
Task: Swap values of two variables without losing data
# Solution 1: Using Python's tuple unpacking (simplest)
first = "Python"
second = "Programming"
print(f"Before swap: first = {first}, second = {second}")
# The swap
first, second = second, first
print(f"After swap: first = {first}, second = {second}")
print("\n" + "="*50)
# Solution 2: Using a temporary variable (traditional way)
a = "Hello"
b = "World"
print(f"Before swap: a = {a}, b = {b}")
# Create temporary variable
temp = a
a = b
b = temp
print(f"After swap: a = {a}, b = {b}")
Exercise 6: Shopping Cart#
Task: Calculate total cost with variables for item name, price, quantity, and tax rate
# Solution
item_name = "Laptop"
price = 899.99
quantity = 2
tax_rate = 0.08 # 8%
# Calculate subtotal
subtotal = price * quantity
# Calculate tax
tax = subtotal * tax_rate
# Calculate total
total = subtotal + tax
# Display receipt
print("=" * 40)
print(" SHOPPING CART RECEIPT")
print("=" * 40)
print(f"Item: {item_name}")
print(f"Price: ${price:.2f}")
print(f"Quantity: {quantity}")
print("-" * 40)
print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax ({tax_rate*100}%): ${tax:.2f}")
print("=" * 40)
print(f"TOTAL: ${total:.2f}")
print("=" * 40)
03 - Basic Operations and Conditionals#
Solutions for exercises from 03_basic_operations_and_conditionals.ipynb
Exercise 1: Calculator#
Task: Perform all arithmetic operations on two numbers
# Solution
num1 = 25
num2 = 4
print(f"Number 1: {num1}")
print(f"Number 2: {num2}")
print("\nResults:")
print("=" * 30)
print(f"Addition: {num1} + {num2} = {num1 + num2}")
print(f"Subtraction: {num1} - {num2} = {num1 - num2}")
print(f"Multiplication: {num1} * {num2} = {num1 * num2}")
print(f"Division: {num1} / {num2} = {num1 / num2:.2f}")
print(f"Integer Division: {num1} // {num2} = {num1 // num2}")
print(f"Modulus (Remainder): {num1} % {num2} = {num1 % num2}")
print(f"Exponentiation: {num1} ** {num2} = {num1 ** num2}")
Exercise 2: Even or Odd#
Task: Check if a number is even or odd
# Solution
number = 17
if number % 2 == 0:
print(f"{number} is EVEN")
else:
print(f"{number} is ODD")
# Test with multiple numbers
print("\nTesting multiple numbers:")
test_numbers = [10, 15, 22, 7, 100, 33]
for num in test_numbers:
if num % 2 == 0:
print(f"{num} is EVEN")
else:
print(f"{num} is ODD")
Exercise 3: Temperature Checker#
Task: Classify temperature as cold, comfortable, or hot
# Solution
temperature = 75
if temperature < 60:
print(f"{temperature}°F is COLD - wear a jacket!")
elif temperature <= 75:
print(f"{temperature}°F is COMFORTABLE - perfect weather!")
else:
print(f"{temperature}°F is HOT - stay hydrated!")
# Test various temperatures
print("\nTesting different temperatures:")
temps = [32, 55, 68, 75, 85, 95]
for temp in temps:
if temp < 60:
status = "COLD"
elif temp <= 75:
status = "COMFORTABLE"
else:
status = "HOT"
print(f"{temp}°F: {status}")
Exercise 4: Age Categorizer#
Task: Categorize age into Child, Teen, Adult, or Senior
# Solution
age = 25
if age <= 12:
category = "Child"
elif age <= 19:
category = "Teen"
elif age <= 59:
category = "Adult"
else:
category = "Senior"
print(f"Age {age}: {category}")
# Test with various ages
print("\nAge Categories:")
test_ages = [5, 10, 15, 18, 25, 40, 60, 75]
for test_age in test_ages:
if test_age <= 12:
cat = "Child"
elif test_age <= 19:
cat = "Teen"
elif test_age <= 59:
cat = "Adult"
else:
cat = "Senior"
print(f"Age {test_age}: {cat}")
Exercise 5: Login System#
Task: Create a simple login checker
# Solution
# Correct credentials
correct_username = "admin"
correct_password = "python123"
# User input (in real program, use input())
entered_username = "admin"
entered_password = "python123"
# Check both username and password
if entered_username == correct_username and entered_password == correct_password:
print("✓ Login successful! Welcome back.")
else:
print("✗ Login failed. Incorrect username or password.")
# More detailed version
print("\n" + "="*40)
print("Testing different scenarios:")
print("="*40)
test_cases = [
("admin", "python123", "Both correct"),
("admin", "wrong", "Wrong password"),
("user", "python123", "Wrong username"),
("wrong", "wrong", "Both wrong")
]
for username, password, description in test_cases:
if username == correct_username and password == correct_password:
result = "✓ Success"
else:
result = "✗ Failed"
print(f"{description}: {result}")
Exercise 6: Ticket Pricing#
Task: Calculate movie ticket price based on age and day
# Solution
base_price = 15
age = 70
day = "Tuesday"
# Start with base price
ticket_price = base_price
# Apply age discount
if age < 12 or age >= 65:
ticket_price = ticket_price * 0.5 # 50% off
discount_reason = "child/senior discount"
# Apply Tuesday discount
elif day == "Tuesday":
ticket_price = ticket_price * 0.7 # 30% off
discount_reason = "Tuesday special"
else:
discount_reason = "no discount"
print(f"Age: {age}")
print(f"Day: {day}")
print(f"Base price: ${base_price}")
print(f"Applied: {discount_reason}")
print(f"Final price: ${ticket_price:.2f}")
# Test multiple scenarios
print("\n" + "="*50)
print("Ticket Pricing Scenarios:")
print("="*50)
scenarios = [
(10, "Friday"), # Child
(25, "Tuesday"), # Tuesday special
(70, "Saturday"), # Senior
(30, "Saturday"), # Regular price
]
for test_age, test_day in scenarios:
price = base_price
if test_age < 12 or test_age >= 65:
price = price * 0.5
reason = "child/senior"
elif test_day == "Tuesday":
price = price * 0.7
reason = "Tuesday special"
else:
reason = "regular"
print(f"Age {test_age}, {test_day}: ${price:.2f} ({reason})")
04 - Intro to AI and ML#
Solutions for exercises from 04_intro_to_ai_and_ml.ipynb
Exercise 1: Age-Based Activity Recommender#
Task: Recommend activity based on age
# Solution
def recommend_activity(age):
"""Recommend an activity based on age."""
if age <= 12:
return "Play in the park"
elif age <= 19:
return "Join a sports team"
elif age <= 59:
return "Go hiking or biking"
else:
return "Take a relaxing walk"
# Test the function
test_ages = [8, 15, 30, 70]
for age in test_ages:
activity = recommend_activity(age)
print(f"Age {age}: {activity}")
Exercise 2: Simple Grade Predictor#
Task: Predict grade based on homework hours pattern
# Solution
def predict_grade(homework_hours):
"""
Predict grade based on homework hours.
Pattern: each hour adds 20 points to base of 40.
"""
predicted_grade = 40 + (homework_hours * 20)
# Cap at 100
if predicted_grade > 100:
predicted_grade = 100
return predicted_grade
# Test the predictor
print("Grade Predictions:")
for hours in range(0, 6):
grade = predict_grade(hours)
print(f"{hours} hours of homework → Grade: {grade}")
Exercise 3: Movie Genre Classifier#
Task: Classify movie genre based on keywords in description
# Solution
def classify_movie(description):
"""
Classify movie genre based on keywords.
"""
description_lower = description.lower()
if any(word in description_lower for word in ["space", "robot", "future"]):
return "Sci-Fi"
elif any(word in description_lower for word in ["love", "heart", "relationship"]):
return "Romance"
elif any(word in description_lower for word in ["laugh", "funny", "comedy"]):
return "Comedy"
elif any(word in description_lower for word in ["fight", "explosion", "chase"]):
return "Action"
else:
return "Drama"
# Test cases
movies = [
"A story about robots taking over the future",
"A heartwarming tale of love and relationships",
"A funny comedy about a cat detective",
"An action-packed adventure with explosions",
"A deep story about life"
]
for movie in movies:
genre = classify_movie(movie)
print(f"'{movie[:40]}...' → {genre}")
Exercise 4: Music Recommender#
Task: Create a music recommendation system
# Solution
def music_recommender(genre):
"""
Recommend songs based on genre preference.
"""
music_library = {
"pop": ["Shake It Off", "Blinding Lights", "Levitating"],
"rock": ["Bohemian Rhapsody", "Stairway to Heaven", "Sweet Child O' Mine"],
"hip-hop": ["Lose Yourself", "HUMBLE.", "Sicko Mode"],
"classical": ["Für Elise", "Moonlight Sonata", "Symphony No. 5"],
"jazz": ["Take Five", "So What", "All Blues"]
}
genre_lower = genre.lower()
if genre_lower in music_library:
return music_library[genre_lower]
else:
return ["No recommendations available for this genre"]
# Test the recommender
genres = ["Pop", "Rock", "Hip-Hop", "Classical", "Country"]
for genre in genres:
recommendations = music_recommender(genre)
print(f"\n{genre}:")
for i, song in enumerate(recommendations, 1):
print(f" {i}. {song}")
Exercise 5: Simple Password Strength Checker#
Task: Check password strength based on length and character types
# Solution
def check_password_strength(password):
"""
Check password strength.
"""
length = len(password)
has_upper = any(c.isupper() for c in password)
has_digit = any(c.isdigit() for c in password)
if length < 8:
return "Weak"
elif length >= 8 and has_upper:
return "Medium"
elif length >= 12 and has_upper and has_digit:
return "Strong"
else:
return "Medium"
# Test passwords
test_passwords = [
"pass", # Weak (too short)
"password", # Medium (8+ chars, no upper)
"Password", # Medium (8+ chars with upper)
"Password123", # Strong (12+ chars, upper, digit)
]
print("Password Strength Analysis:")
print("="*50)
for pwd in test_passwords:
strength = check_password_strength(pwd)
print(f"{pwd:20s} → {strength}")
Exercise 6: Temperature Predictor#
Task: Predict temperature for any month based on pattern
# Solution
def predict_temperature(month):
"""
Predict temperature based on month.
Pattern: Coldest in winter, warmest in summer.
"""
# Temperature data for each month
temperatures = {
1: 10, # January
2: 12, # February
3: 15, # March
4: 18, # April
5: 22, # May
6: 25, # June
7: 28, # July
8: 27, # August
9: 24, # September
10: 20, # October
11: 15, # November
12: 11 # December
}
if month in temperatures:
return temperatures[month]
else:
return None
# Month names for display
month_names = ["", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
# Predict for all months
print("Temperature Predictions (°C):")
print("="*40)
for month_num in range(1, 13):
temp = predict_temperature(month_num)
print(f"{month_names[month_num]:12s} (Month {month_num:2d}): {temp}°C")
05 - Computing Fundamentals#
Solutions for exercises from 05_computing_fundamentals.ipynb
Exercise 1: Binary Converter#
Task: Convert decimal to binary and vice versa
# Solution
def decimal_to_binary(decimal_num):
"""Convert decimal to binary."""
return bin(decimal_num)[2:] # [2:] removes '0b' prefix
def binary_to_decimal(binary_str):
"""Convert binary to decimal."""
return int(binary_str, 2)
# Test conversions
print("Decimal to Binary:")
decimal_numbers = [10, 25, 42, 100, 255]
for num in decimal_numbers:
binary = decimal_to_binary(num)
print(f"{num:3d} → {binary:>8s}")
print("\nBinary to Decimal:")
binary_numbers = ["1010", "11001", "101010", "1100100", "11111111"]
for binary in binary_numbers:
decimal = binary_to_decimal(binary)
print(f"{binary:>8s} → {decimal:3d}")
# Verify round-trip conversion
print("\nRound-trip verification:")
original = 42
binary = decimal_to_binary(original)
back_to_decimal = binary_to_decimal(binary)
print(f"{original} → {binary} → {back_to_decimal}")
print(f"Match: {original == back_to_decimal}")
Exercise 2: Word Analyzer#
Task: Convert letters to ASCII and back
# Solution
def analyze_word(word):
"""Convert word to ASCII codes and display patterns."""
print(f"Analyzing: '{word}'")
print("="*40)
ascii_codes = []
for i, char in enumerate(word):
code = ord(char)
ascii_codes.append(code)
print(f"Position {i}: '{char}' → ASCII {code}")
print("\nASCII codes:", ascii_codes)
# Convert back
reconstructed = ''.join(chr(code) for code in ascii_codes)
print(f"Reconstructed: '{reconstructed}'")
print(f"Match: {word == reconstructed}")
return ascii_codes
# Test
analyze_word("Python")
print("\n")
analyze_word("AI")
Exercise 3: Storage Calculator#
Task: Calculate storage for different media types
# Solution
def calculate_storage(media_type, quantity):
"""
Calculate storage needed for different media.
"""
# Storage per unit in bytes
storage_sizes = {
"text_char": 1, # 1 byte per character
"photo": 3 * 1024 * 1024, # 3 MB per photo
"song": 4 * 1024 * 1024, # 4 MB per song
"video_min": 50 * 1024 * 1024 # 50 MB per minute
}
if media_type not in storage_sizes:
return None
total_bytes = storage_sizes[media_type] * quantity
# Convert to appropriate units
if total_bytes < 1024:
return f"{total_bytes} bytes"
elif total_bytes < 1024 * 1024:
return f"{total_bytes / 1024:.2f} KB"
elif total_bytes < 1024 * 1024 * 1024:
return f"{total_bytes / (1024 * 1024):.2f} MB"
else:
return f"{total_bytes / (1024 * 1024 * 1024):.2f} GB"
# Test calculations
print("Storage Calculations:")
print("="*50)
print(f"500 text characters: {calculate_storage('text_char', 500)}")
print(f"100 photos: {calculate_storage('photo', 100)}")
print(f"50 songs: {calculate_storage('song', 50)}")
print(f"30 minutes of video: {calculate_storage('video_min', 30)}")
Exercise 4: Secret Message Encoder#
Task: Encode and decode messages using ASCII shift
# Solution
def encode_message(message, shift=3):
"""
Encode message by shifting ASCII codes.
"""
encoded = ""
for char in message:
ascii_code = ord(char)
shifted_code = ascii_code + shift
encoded += chr(shifted_code)
return encoded
def decode_message(encoded, shift=3):
"""
Decode message by reversing the shift.
"""
decoded = ""
for char in encoded:
ascii_code = ord(char)
original_code = ascii_code - shift
decoded += chr(original_code)
return decoded
# Test the encoder/decoder
original_message = "Hello Python!"
print(f"Original: {original_message}")
encoded = encode_message(original_message, shift=5)
print(f"Encoded: {encoded}")
decoded = decode_message(encoded, shift=5)
print(f"Decoded: {decoded}")
print(f"\nMatch: {original_message == decoded}")
# Test with different shifts
print("\nDifferent shift values:")
for shift_val in [1, 3, 5, 10]:
enc = encode_message("AI", shift_val)
dec = decode_message(enc, shift_val)
print(f"Shift {shift_val:2d}: AI → {enc} → {dec}")
Exercise 5: Download Time Calculator#
Task: Calculate download time based on file size and internet speed
# Solution
def calculate_download_time(file_size_mb, speed_mbps):
"""
Calculate download time.
file_size_mb: File size in megabytes
speed_mbps: Internet speed in megabits per second
"""
# Convert MB to Mb (1 MB = 8 Mb)
file_size_mb_bits = file_size_mb * 8
# Calculate time in seconds
time_seconds = file_size_mb_bits / speed_mbps
# Convert to appropriate units
if time_seconds < 60:
return f"{time_seconds:.2f} seconds"
elif time_seconds < 3600:
minutes = time_seconds / 60
return f"{minutes:.2f} minutes"
else:
hours = time_seconds / 3600
return f"{hours:.2f} hours"
# Test cases
print("Download Time Calculations:")
print("="*60)
scenarios = [
(10, 100, "Small file, fast internet"),
(100, 50, "Medium file, medium internet"),
(1000, 10, "Large file, slow internet"),
(5000, 100, "Very large file, fast internet")
]
for size, speed, description in scenarios:
time = calculate_download_time(size, speed)
print(f"{description}:")
print(f" {size} MB at {speed} Mbps → {time}")
print()
Exercise 6: Computer Spec Analyzer#
Task: Rate computer specs and determine overall performance category
# Solution
def analyze_computer_specs(cpu_speed, ram_gb, storage_gb):
"""
Analyze computer specs and rate performance.
"""
# Rate CPU
if cpu_speed > 3.0:
cpu_rating = "Fast"
cpu_score = 3
elif cpu_speed >= 2.0:
cpu_rating = "Medium"
cpu_score = 2
else:
cpu_rating = "Slow"
cpu_score = 1
# Rate RAM
if ram_gb >= 16:
ram_rating = "High"
ram_score = 3
elif ram_gb >= 8:
ram_rating = "Medium"
ram_score = 2
else:
ram_rating = "Low"
ram_score = 1
# Rate Storage
if storage_gb >= 500:
storage_rating = "Large"
storage_score = 3
elif storage_gb >= 250:
storage_rating = "Medium"
storage_score = 2
else:
storage_rating = "Small"
storage_score = 1
# Calculate overall rating
total_score = cpu_score + ram_score + storage_score
if total_score >= 8:
overall = "High Performance"
elif total_score >= 6:
overall = "Good Performance"
else:
overall = "Basic Performance"
# Display results
print("Computer Specification Analysis:")
print("="*50)
print(f"CPU: {cpu_speed} GHz → {cpu_rating} (Score: {cpu_score})")
print(f"RAM: {ram_gb} GB → {ram_rating} (Score: {ram_score})")
print(f"Storage: {storage_gb} GB → {storage_rating} (Score: {storage_score})")
print("-"*50)
print(f"Total Score: {total_score}/9")
print(f"Overall Rating: {overall}")
print("="*50)
return overall
# Test different computer configurations
print("\n### Gaming PC ###")
analyze_computer_specs(3.5, 16, 1000)
print("\n### Office PC ###")
analyze_computer_specs(2.5, 8, 256)
print("\n### Budget Laptop ###")
analyze_computer_specs(1.8, 4, 128)
Summary#
Congratulations! You’ve reviewed solutions for all 29 exercises in the Easy level.
Key Takeaways#
Multiple Approaches: Many problems can be solved in different ways
Practice Makes Perfect: The more you code, the better you get
Understanding > Memorizing: Focus on understanding concepts, not memorizing solutions
Test Your Code: Always test with different inputs
Build Incrementally: Start simple, then add features
Next Steps#
Try modifying these solutions to add new features
Combine concepts from different exercises
Move on to Medium level challenges
Build your own projects using what you’ve learned
Remember: If your solution works and is readable, it’s a good solution! There’s rarely one “perfect” way to solve a problem.