🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Web & Software Development › PHP and Python Web Programming › Lesson 7
TEC-WEB46-03 · Lesson 7 · 14 clock hours · lab

Python Control Flow, Functions, and Modules

Objective. Students write Python programs using if/elif/else, for and while loops, list comprehensions, user-defined functions with default and keyword arguments, and import statements for standard library modules, mapping to PCEP exam objectives PE2 and PE3

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Python Control Flow, Functions, and Modules

This lab lesson covers three pillars of practical Python programming that appear directly on the PCEP (Certified Entry-Level Python Programmer) exam: control flow, user-defined functions, and the standard library. Master these and you can build real programs that make decisions, repeat work efficiently, and reuse trusted code.

Control Flow: Making Decisions and Repeating Work

Python uses `if`, `elif`, and `else` to branch based on conditions. Indentation is not optional — Python uses it to define code blocks, so every branch body must be consistently indented (four spaces is the standard style).

```python

grade = 85

if grade >= 90:

print("A")

elif grade >= 80:

print("B")

else:

print("Below B")

```

For repetition, Python offers two loops. A `for` loop iterates over any sequence (list, string, range). A `while` loop runs as long as a condition remains `True`. Use `break` to exit a loop early and `continue` to skip to the next iteration.

```python

for i in range(1, 6): # prints 1 through 5

print(i)

count = 0

while count < 3:

print(count)

count += 1

```

List comprehensions give you a compact way to build lists from loops and conditions in a single line:

```python

squares = [x**2 for x in range(1, 11)] # [1, 4, 9, ... 100]

evens = [x for x in range(20) if x % 2 == 0] # even numbers 0-18

```

Use comprehensions when the intent stays clear. Avoid nesting them so deeply that readability suffers.

User-Defined Functions

Functions let you name and reuse a block of code. Define them with `def`, return values with `return`, and document them with a docstring — a string literal immediately after the `def` line, enclosed in triple quotes.

```python

def greet(name, greeting="Hello"):

"""Return a greeting string for the given name.

Parameters:

name (str): The person's name.

greeting (str): The greeting word. Defaults to 'Hello'.

Returns:

str: The formatted greeting.

"""

return f"{greeting}, {name}!"

print(greet("Ana")) # Hello, Ana!

print(greet("Ana", "Hi")) # Hi, Ana!

print(greet(greeting="Hey", name="Bo")) # keyword arguments

```

Default arguments give a parameter a fallback value when the caller omits it. Keyword arguments let the caller name parameters explicitly, making calls easier to read and order-independent.

Functions should do one thing, be named with a verb phrase, and always include a docstring — this is not just good practice, it is a PCEP exam expectation.

Exception Handling Basics

Real programs receive unpredictable input. A `try/except` block lets you catch errors without crashing:

```python

try:

value = int(input("Enter a number: "))

except ValueError:

print("That was not a whole number. Please try again.")

```

Catch only the specific exception you expect (`ValueError`, `FileNotFoundError`, etc.) rather than using a bare `except:` clause, which silently swallows all errors and makes debugging difficult.

Importing Standard Library Modules

Python ships with a large standard library. You pull in a module with an `import` statement:

```python

import math

import os

import datetime

import random

print(math.sqrt(144)) # 12.0

print(os.getcwd()) # current working directory

print(datetime.date.today()) # today's date

print(random.randint(1, 100)) # random integer 1-100

```

You can also import specific names with `from module import name`, or create an alias with `import module as alias`. Know both forms for the PCEP exam.

| Module | Key Use |

|--------|---------|

| `math` | Mathematical functions: `sqrt`, `floor`, `ceil`, `pi` |

| `os` | Operating system interaction: paths, directory listings |

| `datetime` | Dates, times, and formatting |

| `random` | Random numbers, shuffling, sampling |

Safety and Professional Practice

Web and software development carries its own safety responsibilities. Never run untested scripts against production data or live servers. Validate and sanitize all user input before using it in file paths, database queries, or shell commands — raw input that reaches an OS call can delete files or expose data. Keep credentials (passwords, API keys) out of source code; use environment variables or configuration files excluded from version control. Save your work frequently and use version control (Git) so you can recover from errors. In a lab environment, work only in your assigned directory and do not access classmates' files.

Connecting to the PCEP Exam

The PCEP syllabus groups objectives into sections. The activities in this lesson map directly to PE2 (functions and the function environment) and PE3 (exception handling). When you sit the exam, expect questions on correct syntax, what a function returns, how default arguments work, what happens when an exception is not caught, and how to import a module. Practice writing code by hand as well as in VS Code — reading code and predicting output is a major exam skill.

Key terms8

Control flowThe order in which Python executes statements; altered by conditionals (if/elif/else) and loops (for, while).
List comprehensionA concise syntax for building a new list by applying an expression to each item in an iterable, optionally filtered by a condition, all within square brackets.
Default argumentA function parameter that has a pre-assigned value used when the caller does not supply that argument.
Keyword argumentA function call technique where arguments are passed by naming the parameter explicitly, allowing any order.
DocstringA string literal placed immediately after a def (or class) statement, enclosed in triple quotes, that documents the function's purpose, parameters, and return value.
Exception handlingUsing try/except blocks to catch and respond to runtime errors without allowing the program to crash.
Standard libraryThe collection of modules included with every Python installation (math, os, datetime, random, etc.) that provide pre-built, tested functionality.
import statementThe Python keyword that loads a module into the current script, making the module's functions and variables available.
In class: Students build a number-guessing game using a while loop, random module, and a function that validates input; they must handle non-integer input gracefully using a try/except block — PCEP objective PE3 (exception handling basics) · PCEP-aligned function drill: students write ten functions of increasing complexity (factorial, palindrome check, Fibonacci sequence, list flattening) and annotate each with a docstring explaining parameters and return value — PCEP objective PE2 · Module exploration lab: students use at least four standard library modules (math, os, datetime, random) in a single script that performs a practical task (e.g., a directory report showing file counts and dates); they document each module's role in their lab log
Materials: Python 3 docs, Python Institute PCEP exam syllabus, VS Code, Python REPL, student lab log template
Check: Number-guessing game handles all edge cases correctly (non-integer, out-of-range, correct guess message); function drill produces correct output for all ten functions; lab log entries complete — pass requires all three deliverables accepted by instructor

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

PCEP PE2 – Control flow
1. A student writes the following code. What is printed? ```python x = 15 if x > 20: print("A") elif x > 10: print("B") elif x > 5: print("C") else: print("D") ```
PCEP PE2 – Data collections and comprehensions
2. Which line of code correctly creates a list of all odd numbers from 1 through 9 using a list comprehension?
PCEP PE2 – Functions and default arguments
3. A function is defined as: ```python def power(base, exp=2): return base ** exp ``` What does `power(3)` return?
PCEP PE3 – Exception handling
4. A student wants to catch only the error raised when a user types text instead of a number. Which except clause is most appropriate?
PCEP PE2 – Modules and import
5. Which import statement makes the `randint` function available so it can be called as `randint(1, 6)`?
PCEP PE2 – Control flow and loops
6. A while loop is written as: ```python n = 1 while n < 5: print(n) n += 1 ``` How many lines of output does this produce?
PCEP PE2 – Functions and programming style
7. What is the primary purpose of a docstring in a Python function?
PCEP PE3 – Input handling and exception awareness
8. A student writes a number-guessing game. The code below has an issue: ```python guess = input("Guess: ") if guess == secret: print("Correct!") ``` `secret` is an integer. What is the most likely bug?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.