Bridge Academy.
PYTHON CONCEPTS · SHARED REFERENCE

Python Concepts

Learn the big idea first, then jump into the matching Level I or Level II notebooks. This page uses one shared explanation for both cohorts, while keeping the materials links separate.

QUICK JUMP
LESSON 010
Intro to Programming & Python
Programming means giving exact instructions to a computer. Python is the language students use to turn ideas into working code.
LESSON 020
Variables
Variables let students store information under a name so they can reuse, change, and print it later.
LESSON 030
Data Types
Python values come in different data types such as integers, decimals, text, and booleans. The type affects what students can do with the value.
LESSON 040
Operators
Operators are the symbols Python uses for arithmetic, comparison, and combination of values.
LESSON 050
Built-in Functions & I/O
Built-in functions are ready-to-use tools such as print, input, len, round, min, and max.
LESSON 060
Strings
Strings are ordered text values. Students can index, slice, search, and transform them without changing the original string in place.
LESSON 070
Lists
Lists store ordered collections of values that students can grow, shrink, reorder, and loop through.
LESSON 080
Dictionaries
Dictionaries map keys to values, making them useful for labeled information such as profiles, prices, records, and lookups.
LESSON 090
Tuples
Tuples are ordered collections like lists, but they are meant to stay unchanged after creation.
LESSON 100
Data Iteration
Loops repeat work so students can process many values, build totals, generate patterns, and automate repetition.
LESSON 110
Conditional Flow
Conditionals let programs make choices. Students use if, elif, and else to run different code based on a test.
LESSON 120
Python Functions
Functions package reusable logic into a named block so students can call it whenever they need the same job done again.
LESSON 130
Error Handling
Error handling helps programs respond safely when something goes wrong instead of crashing immediately.
LESSON 140
List Comprehensions
List comprehensions build a new list in one compact expression, often replacing a short loop-and-append pattern.
LESSON 150
Lambda & Functional Tools
Lambda and functional tools let students pass small functions into helpers like sorted, map, and filter.
LESSON 160
Advanced Functions
Advanced function topics show how Python handles flexible arguments and treats functions as values that can be passed or returned.
LESSON 170
OOP Introduction
Object-oriented programming groups data and behavior together inside classes and objects.
LESSON 180
File I/O
File I/O lets programs read saved information from files and write new information back out.
LESSON 190
Advanced Exception Handling
Advanced exception handling adds else, finally, custom raises, and clearer error design for larger programs.
LESSON 200
Modules & Packages
Modules and packages organize code so programs can reuse built-in tools, third-party libraries, and student-written helpers.
LESSON 010 · PCEP

Intro to Programming & Python

Programming means giving exact instructions to a computer. Python is the language students use to turn ideas into working code.

basicssyntaxinterpreter

What This Means

A program is a list of instructions that runs in order. Python reads those instructions, checks the syntax, and then executes them.

  • The computer only does what the code says, not what we meant.
  • Python uses indentation to show structure, so spacing matters.
  • Comments help humans read code, but Python ignores them.

Why It Matters

This concept gives students their mental model for everything else on the site. If they understand that Python runs clear, ordered instructions, later topics feel much less mysterious.

Python Syntax Toolbox

print("Hello, Bridge Academy!")
# This line is a comment
Start simple

The first win is just making something run correctly and understanding why it ran.

Worked Example

print("Welcome to Python")
print("Line 2 runs after line 1")

Students see that each line runs from top to bottom and produces visible output.

Common Mistakes

  • Forgetting quotes around text
  • Missing a closing parenthesis in print(...)
  • Adding spaces before top-level code when no block has started
LESSON 020 · PCEP

Variables

Variables let students store information under a name so they can reuse, change, and print it later.

assignmentnamingf-strings

What This Means

A variable is a label attached to a value. Instead of repeating the same value again and again, students give it a name and use that name later.

  • Assignment uses = to store a value.
  • Reassignment changes what the name points to.
  • F-strings let students place variables inside sentences.

Why It Matters

Variables are the bridge from one-line output to real programs. Once students can store and update values, they can model scores, names, totals, timers, and much more.

Python Syntax Toolbox

city = "Atlanta"
score = 10
score = score + 5
print(f"Score: {score}")

Worked Example

price = 24.99
rate = 0.07
total = price * (1 + rate)
print(f"Total: ${total:.2f}")
Why this works

The program stores each value first, then combines them in a readable expression.

Common Mistakes

  • Putting quotes around the variable name when you want the value
  • Using spaces inside a variable name
  • Forgetting the f in front of an f-string
LESSON 030 · PCEP

Data Types

Python values come in different data types such as integers, decimals, text, and booleans. The type affects what students can do with the value.

intfloatstrbool

What This Means

A data type tells Python what kind of value it is working with. Numbers, text, and True/False values behave differently.

  • int stores whole numbers
  • float stores decimal numbers
  • str stores text
  • bool stores True or False

Why It Matters

Students need this concept to predict program behavior. It explains why 3 + 4 works, why text needs quotes, and why some conversions need casting.

Python Syntax Toolbox

age = 12
height = 1.52
name = "Ava"
is_ready = True
print(type(height))
text_number = "42"
real_number = int(text_number)

Worked Example

raw_temp = "21.5"
temp_c = float(raw_temp)
print(temp_c + 3)

The string must be converted before Python can do number math with it.

Common Mistakes

  • Trying to add a string directly to a number
  • Assuming floats behave exactly like integers
  • Forgetting that input() returns text
LESSON 040 · PCEP

Operators

Operators are the symbols Python uses for arithmetic, comparison, and combination of values.

mathprecedencecomparison

What This Means

Operators tell Python what action to perform between values. They cover arithmetic, string joining, and logical comparison.

  • +, -, *, /, //, %, ** handle numeric work
  • Comparison operators produce True or False
  • Parentheses control the order of operations

Why It Matters

Students use operators in nearly every lesson. They need them for formulas, conditions, score updates, and later algorithmic work.

Python Syntax Toolbox

print(2 + 3 * 4)
print((2 + 3) * 4)
print(10 % 3)
print(2 ** 5)

Worked Example

price = 24.99
rate = 0.065
total = price * (1 + rate)
print(f"${total:.2f}")
Reasoning step

The parentheses make Python compute the tax multiplier before the final multiplication.

Common Mistakes

  • Forgetting operator precedence
  • Using / when you wanted integer division //
  • Mixing comparison logic with arithmetic without parentheses
LESSON 050 · PCEP

Built-in Functions & I/O

Built-in functions are ready-to-use tools such as print, input, len, round, min, and max.

functionsinputoutput

What This Means

Python ships with useful functions that students can call right away. These functions save time and make programs more expressive.

  • print(...) shows output
  • input(...) reads user text
  • len(...), round(...), min(...), max(...) analyze or reshape values

Why It Matters

This topic helps students move from fixed examples to interactive programs. It also introduces the habit of reaching for tools instead of rewriting everything by hand.

Python Syntax Toolbox

name = input("What is your name? ")
print(f"Hi, {name}!")
scores = [88, 91, 73]
print(len(scores))
print(max(scores))

Worked Example

raw_price = input("Price? ")
price = float(raw_price)
print(f"${round(price, 2):.2f}")

Students can see the full path: read text, convert it, then format the final answer.

Common Mistakes

  • Forgetting to cast input() before doing number math
  • Writing len without parentheses
  • Using the wrong function when a simpler built-in already exists
LESSON 060 · PCEP

Strings

Strings are ordered text values. Students can index, slice, search, and transform them without changing the original string in place.

textindexingmethods

What This Means

A string is text wrapped in quotes. Python treats it as an ordered sequence of characters, which means students can access one character or a range of characters.

  • Indexing grabs one character
  • Slicing grabs a range
  • String methods create transformed versions of the text

Why It Matters

Strings show up everywhere: names, prompts, file content, DNA sequences, messages, and menu labels. They are also a gentle introduction to sequence thinking.

Python Syntax Toolbox

word = "python"
print(word[0])
print(word[1:4])
print(word.upper())
Immutability

Strings do not change in place. Most string methods return a new string instead.

Worked Example

raw = "  bridge academy  "
clean = raw.strip().title()
print(clean)

The original text stays the same; each method returns a cleaned-up version.

Common Mistakes

  • Using an index that is out of range
  • Forgetting that slice stop positions are excluded
  • Expecting .replace() or .upper() to modify the original string automatically
LESSON 070 · PCEP

Lists

Lists store ordered collections of values that students can grow, shrink, reorder, and loop through.

collectionsappendslicing

What This Means

A list is an ordered collection inside square brackets. Lists are mutable, so students can add, remove, and update elements as a program runs.

  • Lists keep order
  • Indexes start at 0
  • Methods such as append, insert, sort, and pop change the list

Why It Matters

Lists are the first place students manage many values at once. They are essential for scores, inventories, menus, playlists, time-series data, and later algorithms.

Python Syntax Toolbox

fruits = ["apple", "banana", "cherry"]
fruits.append("date")
print(fruits[1])
print(fruits[:2])
Mutable on purpose

Unlike strings and tuples, lists are designed to be edited as the program runs.

Worked Example

temps = [71, 74, 69]
temps.append(73)
avg = sum(temps) / len(temps)
print(f"{avg:.1f}")

The list grows first, then students use other tools to summarize it.

Common Mistakes

  • Confusing an element with its index
  • Writing values = values.sort() and losing the list
  • Mutating a list when a copied version was intended
LESSON 080 · PCEP

Dictionaries

Dictionaries map keys to values, making them useful for labeled information such as profiles, prices, records, and lookups.

mappingkeysrecords

What This Means

A dictionary stores pairs of related information. Instead of using positions like a list, students use keys such as 'name', 'capital', or 'price'.

  • Keys must be unique
  • Lookups happen by key, not by numeric position
  • Methods like keys(), values(), items(), and get() help with iteration and safe access

Why It Matters

Dictionaries feel closer to real data. They let students model records and labeled facts long before they are ready for databases or APIs.

Python Syntax Toolbox

student = {"name": "Ava", "grade": 7}
student["club"] = "Robotics"
print(student["name"])
print(student.get("teacher", "TBD"))

Worked Example

prices = {"AAPL": 184.5, "MSFT": 410.2}
for ticker, price in prices.items():
    print(f"{ticker}: {price}")

The items() view is the cleanest way to loop over both keys and values together.

Common Mistakes

  • Looking up a missing key without get()
  • Assuming dictionary order works like list indexing
  • Forgetting that looping over a dictionary alone gives keys
LESSON 090 · PCEP

Tuples

Tuples are ordered collections like lists, but they are meant to stay unchanged after creation.

immutableunpackingrecords

What This Means

A tuple groups values together in a fixed order. It is useful when the shape of the data should stay stable, such as coordinates or measurement records.

  • Tuples use parentheses
  • They support indexing and slicing
  • Unpacking assigns tuple items into separate variables

Why It Matters

Tuples help students think about fixed records and multiple return values. They also prepare students for cleaner function outputs.

Python Syntax Toolbox

point = (4, 7)
x, y = point
print(x)
print(point[-1])

Worked Example

measurement = (21.4, "C")
value, unit = measurement
print(f"{value} {unit}")
Good fit

Choose a tuple when the collection should stay fixed, not when students need to append or remove items.

Common Mistakes

  • Trying to change a tuple item with assignment
  • Forgetting the comma in a one-item tuple
  • Using a tuple where a list would be easier to update
LESSON 100 · PCEP

Data Iteration

Loops repeat work so students can process many values, build totals, generate patterns, and automate repetition.

forwhilerange

What This Means

A loop repeats a block of code. Students use loops when the same pattern needs to happen for each number, item, character, or record.

  • for loops are great for known sequences
  • while loops are great when a condition controls repetition
  • Accumulators help build totals, counts, and other running results

Why It Matters

Loops are where students start thinking algorithmically. Instead of solving one case, they write a pattern that solves many cases.

Python Syntax Toolbox

for i in range(5):
    print(i)

total = 0
for value in [2, 4, 6]:
    total += value
count = 3
while count > 0:
    print(count)
    count -= 1

Worked Example

scores = [88, 91, 73, 95]
count = 0
for score in scores:
    if score >= 90:
        count += 1
print(count)

This example combines iteration, conditionals, and an accumulator in a way students will reuse often.

Common Mistakes

  • Indenting the loop body incorrectly
  • Forgetting to update the variable inside a while loop
  • Resetting the accumulator inside the loop by accident
LESSON 110 · PCEP

Conditional Flow

Conditionals let programs make choices. Students use if, elif, and else to run different code based on a test.

ifelifboolean

What This Means

A conditional checks whether something is True or False, then chooses which block of code should run.

  • if handles the first test
  • elif adds extra branches
  • else handles the fallback case

Why It Matters

This is the core idea behind decisions in programming: grading rules, menu choices, validation, game logic, and filtering all depend on conditionals.

Python Syntax Toolbox

score = 87
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
else:
    print("Keep practicing")

Worked Example

temp = 38
if temp >= 100.4:
    print("Fever")
else:
    print("Normal range")
Boolean thinking

Each branch should answer one clear question.

Common Mistakes

  • Using = instead of == in a condition
  • Writing overlapping branches in the wrong order
  • Forgetting the colon at the end of if or elif
LESSON 120 · PCEP

Python Functions

Functions package reusable logic into a named block so students can call it whenever they need the same job done again.

defparametersreturn

What This Means

A function is a reusable mini-program with a name. It can take inputs, do work, and optionally return a result.

  • def creates the function
  • Parameters receive input values
  • return sends a result back to the caller

Why It Matters

Functions reduce repetition and make bigger programs easier to read. They also help students think in smaller, testable pieces.

Python Syntax Toolbox

def rectangle_area(length, width):
    return length * width

print(rectangle_area(3, 4))

Worked Example

def greet(name, punctuation="!"):
    print(f"Hello, {name}{punctuation}")

greet("Mia")
greet("Leo", "?")

Students can see both required and optional inputs without needing a long explanation.

Common Mistakes

  • Forgetting to call the function after defining it
  • Printing inside a function when a return value was needed
  • Using variable names inside the function that were never passed in
LESSON 130 · PCEP

Error Handling

Error handling helps programs respond safely when something goes wrong instead of crashing immediately.

tryexceptrobustness

What This Means

Exceptions are Python's way of reporting errors. try/except lets students attempt risky code and choose how to respond if it fails.

  • try contains the risky operation
  • except catches specific error types
  • Good handlers explain the problem or recover safely

Why It Matters

Students stop being afraid of runtime errors when they understand what they mean and how to catch common ones such as ValueError or IndexError.

Python Syntax Toolbox

try:
    age = int(input("Age? "))
except ValueError:
    print("Please enter digits only.")

Worked Example

items = ["pen", "book"]
try:
    print(items[3])
except IndexError:
    print("That position does not exist.")
Specific is better

Catch the narrowest useful exception type first so students learn what actually failed.

Common Mistakes

  • Using a bare except for everything
  • Catching the error but giving no useful message
  • Assuming try/except replaces careful logic and validation
LESSON 140 · PCAP

List Comprehensions

List comprehensions build a new list in one compact expression, often replacing a short loop-and-append pattern.

comprehensionmappingfiltering

What This Means

A list comprehension is a shorter way to create a list from another iterable. It can map values, filter values, or do both in one readable expression.

  • expression comes first
  • the for clause names each item
  • an optional if clause filters items

Why It Matters

This is a PCAP bridge topic because students already know the long form. Now they can compare concise syntax against the loop version and choose what reads best.

Python Syntax Toolbox

squares = [n * n for n in range(6)]
evens = [n for n in range(10) if n % 2 == 0]

Worked Example

temps_f = [68, 72, 77]
temps_c = [round((f - 32) * 5 / 9, 1) for f in temps_f]
print(temps_c)

Common Mistakes

  • Trying to cram too much logic into one expression
  • Forgetting the order: expression, for, optional if
  • Using a comprehension when a normal loop would be clearer
LESSON 150 · PCAP

Lambda & Functional Tools

Lambda and functional tools let students pass small functions into helpers like sorted, map, and filter.

lambdasortedmap/filter

What This Means

A lambda is a small anonymous function. It is often used when students need a quick rule to pass into another function.

  • lambda is best for tiny one-expression functions
  • sorted(..., key=...) is the most common beginner-friendly use
  • map and filter apply a rule across data

Why It Matters

This topic helps Level II students see that functions can be treated like data and passed around when needed.

Python Syntax Toolbox

names = ["Ava", "Liam", "Noah"]
print(sorted(names, key=lambda name: len(name)))
nums = [1, 2, 3, 4]
print(list(filter(lambda n: n % 2 == 0, nums)))

Worked Example

quotes = {"AAPL": 184.5, "MSFT": 410.2, "GOOG": 138.9}
ranked = sorted(quotes.items(), key=lambda item: item[1], reverse=True)
print(ranked[0])

Common Mistakes

  • Using lambda for logic that deserves a named function
  • Forgetting that map and filter return iterables in Python 3
  • Writing a key function that returns the wrong comparison value
LESSON 160 · PCAP

Advanced Functions

Advanced function topics show how Python handles flexible arguments and treats functions as values that can be passed or returned.

argskwargshigher-order

What This Means

Python functions can accept variable numbers of arguments and can also be passed into other functions. This makes code more reusable and configurable.

  • *args collects extra positional arguments
  • **kwargs collects named arguments
  • Functions can be stored, returned, and passed around

Why It Matters

These patterns appear in frameworks, libraries, and reusable utilities. Students do not need them every day, but they help explain more advanced Python code.

Python Syntax Toolbox

def total(*nums):
    return sum(nums)

def describe(**info):
    return info

Worked Example

def apply_twice(fn, value):
    return fn(fn(value))

print(apply_twice(lambda x: x + 3, 4))

Common Mistakes

  • Forgetting that *args becomes a tuple
  • Mixing positional and keyword argument order incorrectly
  • Using clever higher-order patterns where plain code would be clearer
LESSON 170 · PCAP

OOP Introduction

Object-oriented programming groups data and behavior together inside classes and objects.

classobjectmethods

What This Means

A class is a blueprint. An object is a specific thing created from that blueprint, carrying its own data and behavior.

  • __init__ builds the starting state
  • self refers to the current object
  • Methods are functions attached to the class

Why It Matters

Students meet OOP when programs grow beyond isolated functions. It is useful for modeling game pieces, bank accounts, students, robots, and other rich objects.

Python Syntax Toolbox

class Student:
    def __init__(self, name, level):
        self.name = name
        self.level = level

    def intro(self):
        return f"{self.name} is level {self.level}."

ava = Student("Ava", 2)
print(ava.intro())

Worked Example

class Counter:
    def __init__(self):
        self.value = 0

    def bump(self):
        self.value += 1

counter = Counter()
counter.bump()
print(counter.value)

Common Mistakes

  • Forgetting self in method definitions
  • Trying to use instance attributes before creating them
  • Mixing up class names and object names
LESSON 180 · PCAP

File I/O

File I/O lets programs read saved information from files and write new information back out.

openreadwrite

What This Means

File input/output is how programs work with data that lasts after the program stops running.

  • open(...) creates a file connection
  • read, readline, and write interact with the file contents
  • with automatically closes the file when the block ends

Why It Matters

This is the bridge from toy programs to real applications. Students start working with saved logs, reports, inputs, and generated outputs.

Python Syntax Toolbox

with open("notes.txt", "r", encoding="utf8") as handle:
    text = handle.read()
    print(text)

Worked Example

lines = ["Ava\n", "Liam\n"]
with open("students.txt", "w", encoding="utf8") as handle:
    handle.writelines(lines)
Mode matters

Opening a file with w replaces old content, so students should know whether they mean write, append, or read.

Common Mistakes

  • Using the wrong file mode
  • Assuming read() returns numbers instead of text
  • Forgetting that newline characters may still be present
LESSON 190 · PCAP

Advanced Exception Handling

Advanced exception handling adds else, finally, custom raises, and clearer error design for larger programs.

raisefinallycustom errors

What This Means

Beyond basic try/except, Python lets students control what happens after success, after failure, and during cleanup.

  • else runs only when no exception happens
  • finally runs whether an error happened or not
  • raise creates an exception on purpose when the program detects a problem

Why It Matters

This topic helps students move from merely catching errors to designing clear, reliable error behavior in larger codebases.

Python Syntax Toolbox

try:
    value = int("42")
except ValueError:
    print("Bad input")
else:
    print(value)
finally:
    print("Done")

Worked Example

def require_positive(n):
    if n <= 0:
        raise ValueError("n must be positive")
    return n

Common Mistakes

  • Using raise without a clear message
  • Putting success-only logic inside finally
  • Catching broad exceptions so early that real bugs become harder to debug
LESSON 200 · PCAP

Modules & Packages

Modules and packages organize code so programs can reuse built-in tools, third-party libraries, and student-written helpers.

importorganizationreuse

What This Means

A module is a Python file with code inside it. A package is a folder that groups related modules together.

  • import brings names into the current file
  • from ... import ... loads a more specific name
  • Modules let students separate reusable code from main scripts

Why It Matters

Students meet this concept when projects stop fitting in one file. It also explains how Python accesses tools like math, random, or datetime.

Python Syntax Toolbox

import math
from random import randint

print(math.sqrt(81))
print(randint(1, 6))

Worked Example

import math
radius = 3
area = math.pi * radius ** 2
print(f"{area:.2f}")

Common Mistakes

  • Naming a student file the same as a standard library module
  • Forgetting which names came from which import style
  • Writing everything in one file when a helper module would be cleaner