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
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.
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.
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.
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.
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.
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 |
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.
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.
Answer each question, then check it. Nothing is recorded; this is your own practice.
A free tech program — complimentary, as our commitment to get America working. Help us build VoTechWorks. Tell us what works, what doesn’t, and what you want to learn.