Skip to content

Latest commit

Β 

History

History
684 lines (548 loc) Β· 19.3 KB

File metadata and controls

684 lines (548 loc) Β· 19.3 KB

Python Intro Sessions - Session 2 Plan

"Working with Collections & Logic"

Target Audience: Non-engineering Codat colleagues
Duration: 1 hour
Tone: Casual, conversational, fun
Note: Building on Session 1 foundations - assumes familiarity with variables, data types, and basic operations


Session Overview

By the end of this session, participants will be able to store and access collections of data using lists and dictionaries, automate repetitive tasks with for loops, make decisions in your code using if/else, and create simple reusable code blocks with functions.


Notebook Cell Structure

Section 1: Welcome & Session 2 Introduction (5 minutes)

Cell 1 (Markdown):

# πŸš€ Session 2: Working with Collections & Logic

Welcome back! In Session 1, we learned the building blocks of Python - variables, data types, and basic operations. Today we're going to learn how to work with collections of data and add logic to our programs.

## What we'll cover today:
- πŸ“‹ **Lists & Dictionaries** - storing collections of data
- πŸ”„ **For loops** - automating repetitive tasks
- πŸ€” **If/else statements** - making decisions in code
- πŸ› οΈ **Simple functions** - creating reusable code blocks
- 🎯 **A mini-project** combining everything

## Quick recap from Session 1:
We learned that Python can store data in variables and work with different types like strings, integers, and floats. Today we'll learn how to work with multiple pieces of data at once!

Section 2: Lists - Collections of Data (8 minutes)

Cell 2 (Markdown):

## πŸ“‹ Lists: Collections of Data

So far we've stored one piece of information per variable. But what if we want to store multiple related items together? That's where **lists** come in!

**Key characteristics of lists:**
- Hold multiple items in order
- Created using square brackets `[]`
- Items separated by commas
- Can access items by position (starting from 0)

Cell 3 (Code):

# Creating lists - just put items in square brackets
team_members = ["Alice", "Bob", "Charlie", "Diana"]
monthly_sales = [45000, 52000, 38000, 67000]

print("Team:", team_members)
print("Sales:", monthly_sales)

Cell 4 (Markdown):

Notice how we can store different types of data - text names and numbers - in separate lists. Now let's see how to get specific items out:

Cell 5 (Code):

# Accessing items by their position (remember: counting starts at 0!)
print("First member:", team_members[0])    # Position 0 = first item
print("Second member:", team_members[1])   # Position 1 = second item
print("Last sale:", monthly_sales[-1])     # -1 means last item

Cell 6 (Markdown):

Python has some helpful built-in functions for working with lists:

Cell 7 (Code):

# Useful list operations
print("Team size:", len(team_members))        # How many items?
print("Total sales:", sum(monthly_sales))     # Add up all the numbers
print("Highest sale:", max(monthly_sales))    # Find the biggest number

Cell 8 (Markdown):

### Practice exercise
Try creating your own list:

Cell 9 (Code):

# Create a list of your favorite apps and practice accessing them
favorite_apps = ["___", "___", "___"]  # Fill in 3 apps you use daily

print("My apps:", favorite_apps)
print("Top app:", favorite_apps[0])
print("How many apps:", len(favorite_apps))

Section 3: Dictionaries - Data with Labels (8 minutes)

Cell 10 (Markdown):

## 🏷️ Dictionaries: Data with Labels

Lists are great, but sometimes you want to label your data. **Dictionaries** store data as key-value pairs - like a real dictionary with words and definitions.

**Key characteristics of dictionaries:**
- Store data as key-value pairs
- Created using curly braces `{}`
- Access data using descriptive keys instead of numbers
- Perfect for structured data

Cell 11 (Code):

# Creating a dictionary - notice the curly braces and key: value pairs
employee = {
    "name": "Sarah Johnson",
    "department": "Sales", 
    "years": 3,
    "remote": True
}

print("Employee data:", employee)

Cell 12 (Markdown):

Now let's see how to get specific pieces of information out:

Cell 13 (Code):

# Accessing values using their keys (labels)
print("Name:", employee["name"])
print("Department:", employee["department"])
print("Years of experience:", employee["years"])
print("Works remotely?", employee["remote"])

Cell 14 (Markdown):

### When to use lists vs dictionaries

**Use lists for:**
- Simple collections: `["apple", "banana", "orange"]`
- When order matters: `[45000, 52000, 38000]` (monthly progression)

**Use dictionaries for:**
- Labeled data: `{"name": "Alice", "role": "Engineer"}`
- Settings/configurations: `{"theme": "dark", "notifications": True}`

Cell 15 (Markdown):

### Practice exercise
Create your own dictionary:

Cell 16 (Code):

# Practice exercise: Create your work profile
my_profile = {
    "name": "___",
    "department": "___", 
    "coffee_per_day": ___,
    "favorite_tool": "___"
}

print("My profile:", my_profile)
print(f"Hi, I'm {my_profile['name']} from {my_profile['department']}")

Section 4: For Loops - Repeating Actions (6 minutes)

Cell 17 (Markdown):

## πŸ”„ For Loops: Automating Repetitive Tasks

What if you want to do something with every item in a list? **For loops** let you repeat actions automatically.

**Basic syntax:**
```python
for item in list_name:
    # Do something with item

**Cell 18 (Code):**
```python
# Simple example: greet each person in a list
team_members = ["Alice", "Bob", "Charlie"]

for person in team_members:
    print(f"Hello, {person}!")

Cell 19 (Markdown):

See how the loop automatically went through each name? Let's try with numbers:

Cell 20 (Code):

# Loop through a sequence of numbers using range()
print("Counting to 5:")
for i in range(5):  # range(5) gives us 0, 1, 2, 3, 4
    print(f"Count: {i}")

Cell 21 (Markdown):

You can also loop through dictionaries to get each key:

Cell 22 (Code):

# Loop through a dictionary
employee = {"name": "Sarah", "department": "Sales", "years": 3}

for key in employee:
    value = employee[key]
    print(f"{key}: {value}")

Section 5: If/Else - Making Decisions (4 minutes)

Cell 23 (Markdown):

## πŸ€” If/Else: Making Decisions in Code

Sometimes you want your code to do different things based on conditions. **If/else statements** let your code make decisions.

**Basic syntax:**
```python
if condition:
    # Do this if condition is True
else:
    # Do this if condition is False

**Cell 24 (Code):**
```python
# Simple decision making
sales = 55000
target = 50000

if sales >= target:
    print("🎯 Target achieved!")
else:
    print("πŸ“‰ Below target")

Cell 25 (Markdown):

We can also do calculations inside if statements:

Cell 26 (Code):

# Do different calculations based on the condition
if sales >= target:
    bonus = (sales - target) * 0.1  # 10% bonus on excess
    print(f"Bonus earned: Β£{bonus:,.0f}")
else:
    shortfall = target - sales
    print(f"Need Β£{shortfall:,} more to hit target")

Cell 27 (Markdown):

For multiple conditions, use `elif` (else if):

Cell 28 (Code):

# Multiple conditions using elif
coffee_count = 3

if coffee_count <= 2:
    print("β˜• Normal amount")
elif coffee_count <= 4:
    print("β˜• Quite a bit!")
else:
    print("β˜• Too much caffeine!")

Section 6: Simple Functions - Reusable Code Blocks (6 minutes)

Cell 29 (Markdown):

## πŸ› οΈ Simple Functions: Reusable Code Blocks

Functions are like little machines - you give them input, they do something, and give you back a result. They help you avoid writing the same code over and over.

**Basic syntax:**
```python
def function_name(input):
    # Do something simple
    return result

**Cell 30 (Code):**
```python
# Very simple functions
def greet_person(name):
    return f"Hello, {name}!"

def add_numbers(a, b):
    return a + b

# Test the functions
greeting = greet_person("Alice")
print(greeting)

total = add_numbers(10, 5)
print(f"10 + 5 = {total}")

Cell 31 (Markdown):

Here's a function that creates email addresses:

Cell 32 (Code):

def make_email(name):
    return f"{name}@codat.io"

# Test it
email = make_email("bob")
print(f"Email: {email}")

Cell 33 (Markdown):

Functions can also make decisions:

Cell 34 (Code):

# A function that makes a simple decision
def check_coffee_intake(cups):
    if cups <= 2:
        return "Perfect amount! β˜•"
    elif cups <= 4:
        return "Getting a bit much! β˜•β˜•"
    else:
        return "Whoa, slow down! β˜•β˜•β˜•"

# Test the function with different inputs
result1 = check_coffee_intake(2)
print(result1)

result2 = check_coffee_intake(5)
print(result2)

Section 7: Final Exercise - Bringing It All Together (12 minutes)

Cell 35 (Markdown):

## 🎯 Final Exercise: Movie Rating Tracker

Let's combine everything we've learned:
- Lists and dictionaries to store data
- Loops to process data
- If/else to make decisions
- Functions to organize our code

We'll build a simple movie tracker!

Cell 36 (Code):

# 🎬 Simple Movie Rating Tracker

# Data storage - list of dictionaries
movies = [
    {"title": "The Lion King", "rating": 9},
    {"title": "Frozen", "rating": 8},
    {"title": "Toy Story", "rating": 10},
    {"title": "Shrek", "rating": 7},
    {"title": "Finding Nemo", "rating": 9}
]

print("Movie data loaded:")
print(f"We have {len(movies)} movies to analyze")

Cell 37 (Markdown):

Now let's create some helper functions:

Cell 38 (Code):

# Simple helper function
def describe_rating(rating):
    if rating >= 9:
        return "⭐ Amazing!"
    elif rating >= 7:
        return "πŸ‘ Good"
    else:
        return "πŸ‘Ž Not great"

# Test our function with different ratings
test_rating1 = describe_rating(9)
print(f"A rating of 9 is: {test_rating1}")

test_rating2 = describe_rating(6)
print(f"A rating of 6 is: {test_rating2}")

Cell 39 (Markdown):

Now let's analyze each movie:

Cell 40 (Code):

# Main analysis
print("🎬 MOVIE REVIEW SUMMARY")
print("=" * 25)

total_rating = 0
great_movies = 0

for movie in movies:
    title = movie["title"]
    rating = movie["rating"]
    description = describe_rating(rating)
    
    total_rating += rating
    if rating >= 9:
        great_movies += 1
    
    print(f"{title}: {rating}/10 - {description}")

Cell 41 (Markdown):

Finally, let's calculate some simple statistics:

Cell 42 (Code):

# Simple movie statistics
average_rating = total_rating / len(movies)

print(f"\nπŸ“Š MOVIE COLLECTION SUMMARY:")
print(f"Total movies: {len(movies)}")
print(f"Total rating points: {total_rating}")
print(f"Average rating: {average_rating:.1f}/10")
print(f"Great movies (9+): {great_movies}")

# Simple recommendation
if average_rating >= 8:
    print("\nπŸŽ‰ You have excellent taste in movies!")
elif average_rating >= 6:
    print("\nπŸ‘ Pretty good movie collection!")
else:
    print("\nπŸ€” Maybe time to find some better movies!")

Cell 43 (Markdown):

## πŸŽ‰ Well Done!

You've successfully completed Session 2! Here's what you can now do:

### βœ… Skills mastered:
- **Lists & Dictionaries**: Store collections of data
- **For loops**: Automate repetitive tasks
- **If/else statements**: Make decisions in code
- **Functions**: Create reusable code blocks
- **Integration**: Combine concepts into working programs

### What's next in Session 3:
- **File handling** - reading and writing data files
- **Error handling** - making your code robust
- **APIs** - connecting to external services
- **Advanced data processing**

You now have the core tools to automate tasks and analyze data!

Appendix

Cell 39 (Markdown):

## Appendix

Advanced List Operations

Cell 40 (Markdown):

### Advanced List Operations

**List comprehensions** - a concise way to create lists:
```python
# Traditional approach
numbers = []
for i in range(10):
    numbers.append(i * 2)

# List comprehension approach  
numbers = [i * 2 for i in range(10)]

# With conditions
even_numbers = [i for i in range(20) if i % 2 == 0]

Useful list methods:

  • list.sort() - sort the list in place
  • list.reverse() - reverse the list
  • list.count(item) - count occurrences of item
  • list.index(item) - find first index of item
  • list.remove(item) - remove first occurrence of item

### Advanced Function Concepts

**Cell 41 (Markdown):**
```markdown
### Advanced Function Concepts

**Default parameters:**
```python
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Alice"))           # Uses default
print(greet("Bob", "Hi"))       # Custom greeting

Variable number of arguments:

def calculate_average(*numbers):
    return sum(numbers) / len(numbers)

print(calculate_average(1, 2, 3, 4, 5))

Lambda functions (anonymous functions):

# Regular function
def double(x):
    return x * 2

# Lambda equivalent
double = lambda x: x * 2

# Often used with built-in functions
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))

### When to Use Each Concept

**Cell 42 (Markdown):**
```markdown
### When to Use Each Concept

**Lists are perfect for:**
- βœ… Collections of similar items (names, numbers, etc.)
- βœ… When order matters
- βœ… When you need to access items by position
- βœ… When the collection size might change

**For loops are ideal for:**
- βœ… Processing every item in a collection
- βœ… Repeating an action a specific number of times
- βœ… Generating sequences or patterns
- βœ… Calculating totals, averages, or other aggregations

**If/else statements shine when:**
- βœ… You need different behavior based on conditions
- βœ… Validating input or data
- βœ… Implementing business rules
- βœ… Handling different scenarios or edge cases

**Functions are valuable for:**
- βœ… Code that you'll use multiple times
- βœ… Complex operations that need a clear name
- βœ… Breaking large problems into smaller pieces
- βœ… Making code easier to test and debug

Implementation Notes

Notebook Structure Summary

  • Main session: 43 cells (24 Markdown, 19 Code)
  • Appendix: 3 cells (3 Markdown) - for extra time or advanced learners
  • Estimated time: 42 minutes (main) + 18-minute buffer for 1 hour total
  • Interactive exercises: 2 practice sections (lists and dictionaries only, final exercise)
  • Theory content: Streamlined with core concepts only
  • Code organization: Each concept split into focused, manageable code cells

Required Setup

  • Packages: None! Standard Python/Jupyter only
  • Dependencies: Base Python 3.x installation (same as Session 1)
  • Environment: Any Jupyter environment (local, Colab, etc.)
  • Prerequisites: Completion of Session 1 or equivalent knowledge

Teaching Strategy

  • Build on Session 1: Assumes familiarity with variables, data types, and basic operations
  • Streamlined approach: Core concepts with minimal interruption, practice in final exercise
  • Bite-sized learning: Code broken into small, manageable cells with explanatory text
  • Practical progression: Each concept builds naturally and is immediately applied
  • Real-world context: Business-focused examples using Codat scenarios
  • Integration focus: Final exercise combines all concepts into a cohesive program
  • Problem-solving approach: Shows how these tools solve real business problems
  • Commentary-driven: Each code cell has context explaining what it demonstrates
  • Logical flow: Lists β†’ Dictionaries β†’ Automation β†’ Decisions β†’ Organization

Facilitator Notes

  • Cell-by-cell approach: Content is broken into small chunks - participants can run each cell and see immediate results
  • Commentary: Each code concept has explanatory text before/after to guide understanding
  • Time management: Keep examples focused - this is a streamlined version to fit 1 hour
  • Prerequisite check: Ensure participants remember Session 1 concepts (variables, strings, basic operations)
  • Zero-indexing emphasis: This is often confusing for beginners - use multiple examples
  • Lists vs dictionaries: Help participants understand when to use each data structure
  • Loop logic: Help participants understand the "for each item" mental model
  • Condition confusion: Watch for = vs == mistakes in if statements
  • Function benefits: Emphasize organization and reusability, not just technical syntax
  • Pacing checkpoints: After lists/dictionaries, after loops and if/else, before final exercise
  • Common stumbling blocks: Indentation errors, indexing mistakes, dictionary key access, condition logic
  • Build confidence: Small cells allow participants to succeed at each step before moving on

Visual Elements Needed

Main Session:

  • Simple diagrams showing list indexing (could be drawn/explained rather than embedded)
  • Flow charts for if/else logic (optional, can be verbal explanation)
  • Emphasis on practical, business-relevant examples over complex visualizations

Appendix (if time permits):

  • Code comparison examples showing different approaches
  • When-to-use decision guides

Success Metrics

By the end of the main session, participants should be able to:

  1. βœ… Create and populate lists with different types of data
  2. βœ… Access specific items from lists using indexing
  3. βœ… Create and use dictionaries with key-value pairs
  4. βœ… Understand when to use lists vs dictionaries
  5. βœ… Use for loops to process every item in a collection
  6. βœ… Use for loops with range() to repeat actions a specific number of times
  7. βœ… Write if/else statements with comparison operators
  8. βœ… Combine if/else with loops for conditional processing
  9. βœ… Define simple functions that take parameters and return values
  10. βœ… Integrate lists, dictionaries, loops, conditionals, and functions into a working program

Bonus objectives (if appendix is covered): 11. βœ… Understand list comprehensions as an alternative to loops 12. βœ… Know about advanced function features (default parameters, *args) 13. βœ… Recognize when to choose each tool for different problems

Bridge to Session 3

The final cell mentions file handling, error handling, and APIs - setting up the next session's focus on more advanced data handling and real-world integration.

Key Differences from Session 1

  • More integration: Concepts are combined more frequently
  • Streamlined content: Focused examples to maintain 1-hour time limit
  • Smaller code chunks: Code cells broken into digestible pieces with explanatory commentary
  • Data structures: Introduction of both lists and dictionaries for data organization
  • Business focus: Examples are more sophisticated and business-oriented
  • Problem-solving: Emphasis on using these tools to solve actual problems
  • Complexity progression: Each section builds more substantially on previous learning
  • Step-by-step guidance: More markdown cells explaining what each code cell demonstrates
  • Practical application: Final exercise combines all concepts into a realistic business tool