🚧 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 › Data Science & Analytics › Python and R for Data Science & Analytics › Lesson 4
TEC-DATA85-03 · Lesson 4 · 12 clock hours · demo

Control Flow, Functions, and Error Handling in Python

Objective. Students write Python functions that use conditionals, loops, and try/except blocks to automate a repeated data-processing task and handle at least two types of runtime errors.

⚠ 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.

Control Flow, Functions, and Error Handling in Python

Writing reliable data pipelines means your code must make decisions, repeat tasks, and recover gracefully when something unexpected happens. This lesson covers three building blocks that make that possible: control flow (conditionals and loops), functions (reusable, named blocks of logic), and error handling (try/except blocks). Together they let you automate a repeated data-processing task without crashing when real-world files are messy—and real-world files are almost always messy.

Why These Skills Matter for Data Work

Data analysts and scientists spend a significant portion of their time cleaning and validating data. A script that crashes the moment it encounters a missing column or a stray text value in a numeric field is not production-ready. Employers—and credentials such as IBM Data Science Professional and CompTIA Data+—expect you to write code that anticipates failure modes and handles them without losing the work already completed.

Conditionals and Boolean Logic

A conditional statement uses `if`, `elif`, and `else` to branch your program based on a condition that evaluates to `True` or `False`.

```python

if value < 0 or value > 500:

print("Out of range")

elif value == 0:

print("Zero detected")

else:

print("Value is acceptable")

```

Comparison operators (`<`, `>`, `==`, `!=`, `<=`, `>=`) and logical operators (`and`, `or`, `not`) let you combine conditions. Keep conditions as simple and readable as possible; complex nested conditionals are a common source of logic errors.

Loops

A `for` loop repeats a block of code for each item in an iterable—a list, a range of numbers, or a collection of filenames.

```python

for filename in file_list:

process_file(filename)

```

A `while` loop continues until a condition becomes `False`. For batch file processing, `for` loops are almost always the right choice because the number of iterations is known in advance.

Use `break` to exit a loop early and `continue` to skip the rest of the current iteration and move to the next one. Avoid using `break` carelessly; it can make code harder to read and debug.

Defining Functions

A function wraps a block of logic under a name so you can call it repeatedly without rewriting the code. The `def` keyword defines a function; `return` sends a value back to the caller.

```python

def validate_value(value, col_name, low, high):

"""Return True if value is within [low, high]; raise ValueError otherwise."""

if not isinstance(value, (int, float)):

raise TypeError(f"{col_name} contains a non-numeric value: {value}")

if value < low or value > high:

raise ValueError(f"{col_name} value {value} is outside [{low}, {high}]")

return True

```

Every function you write for this course must include a docstring—the triple-quoted string immediately after the `def` line—and inline comments on any non-obvious line. Docstrings document what the function expects and returns; they are not optional in professional code.

Raising Exceptions Intentionally

You can signal that something is wrong by raising a built-in exception with `raise`. Two you will use often are:

Raising a descriptive exception is far more useful than silently returning `None` or `False`, because it forces the calling code to deal with the problem explicitly.

try/except Blocks

A `try/except` block lets you attempt an operation and catch specific exceptions if they occur, so the program continues rather than crashing.

```python

try:

validate_value(row[col], col, 0, 500)

except ValueError as e:

print(f"ValueError: {e}")

log_bad_record(filename, row)

except TypeError as e:

print(f"TypeError: {e}")

log_bad_record(filename, row)

except FileNotFoundError as e:

print(f"File not found: {e}")

```

Always catch the most specific exception type you expect. Catching the bare `Exception` class hides bugs. List each exception type separately or group truly equivalent ones with a tuple: `except (ValueError, TypeError) as e:`.

Logging Bad Records

When validation fails, write the bad record to a log file rather than discarding it silently. Use Python's built-in `open()` in append mode (`"a"`) so successive runs add to the log rather than overwriting it.

```python

def log_bad_record(filename, row, log_path="bad_records.txt"):

"""Append a bad record entry to the log file."""

with open(log_path, "a") as log:

log.write(f"{filename} | {row}\n")

```

The `with` statement closes the file automatically even if an error occurs inside the block—always prefer it over manual `open()`/`close()` calls.

Safety and Data Integrity Considerations

In data work, "safety" means protecting the integrity of data and the systems that depend on it. Before running any batch script on real data:

1. Work on copies. Never modify original source files. Keep raw data read-only.

2. Validate inputs before processing. Check that expected columns exist before iterating rows.

3. Limit file path assumptions. Use `os.path.join()` or `pathlib.Path` rather than hard-coded path strings, which break across operating systems.

4. Test on small samples first. Run your script on two or three files before unleashing it on an entire folder.

5. Review your log file after every run to confirm errors are being caught and recorded, not silently swallowed.

These habits mirror the data quality and pipeline reliability expectations tested on CompTIA Data+ and the IBM Data Science Professional Certificate.

Putting It Together

The demo in this lesson builds one function (`validate_value`) and one helper (`log_bad_record`), then wraps them in a `for` loop that processes five CSV files of city traffic counts. After each file, a summary row—filename, total row count, error count—is appended to a results DataFrame. This mirrors the kind of lightweight ETL (extract, transform, load) script you will write on the job and in portfolio projects.

Key terms10

Control flowThe order in which a program executes statements, controlled by conditionals (if/elif/else) and loops (for/while).
FunctionA named, reusable block of Python code defined with `def` that accepts inputs (parameters) and optionally returns a value.
DocstringA triple-quoted string placed immediately after a `def` or `class` statement that documents what the function does, its parameters, and its return value.
ExceptionAn object Python creates when a runtime error occurs; built-in types include ValueError, TypeError, and FileNotFoundError.
try/except blockA code structure that attempts an operation in the `try` clause and catches specific exceptions in one or more `except` clauses, preventing the program from crashing.
raiseThe Python keyword used to deliberately trigger an exception, allowing a function to signal invalid input or an unexpected condition to its caller.
ValueErrorA built-in Python exception raised when a value is the correct type but an unacceptable value, such as a traffic count outside an expected range.
TypeErrorA built-in Python exception raised when an operation is applied to an object of the wrong type, such as a string where a number is required.
Append modeFile open mode (`"a"`) in Python that adds new content to the end of an existing file rather than overwriting it; used here to accumulate log entries across runs.
ETL (Extract, Transform, Load)A data-pipeline pattern in which data is pulled from a source, cleaned or transformed, and written to a destination; the batch script in this lesson is a simple ETL example.
In class: Watch and narrate a step-by-step instructor demo that builds a function validating whether a numeric column value is within an acceptable range, raises a ValueError for out-of-range entries, and logs the bad record to a text file; students replicate the demo independently. · Write a for-loop that reads five CSV files from a folder, calls the validation function on a specified column in each, and appends a summary row (filename, row count, error count) to a results data frame; run and debug until all five files process cleanly. · Intentionally introduce three different errors (wrong file path, mismatched column name, non-numeric value) into copies of the CSV files and confirm that the try/except block catches each one with a descriptive printed message rather than crashing.
Materials: Jupyter Notebook, Python 3.x documentation, five provided CSV files (city traffic counts), instructor demo script, lab log
Check: Function passes all three deliberately broken test cases with correct error messages and processes all five clean files without crashing; code includes docstring and inline comments — maps to IBM Data Science and CompTIA Data+ scripting domains.

Practice check8

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

IBM Data Science – Python programming fundamentals
1. Which Python keyword is used to deliberately trigger an exception inside a function?
CompTIA Data+ – scripting and automation
2. A function is called inside a try block and raises a TypeError. Which except clause will catch it?
IBM Data Science – Python file I/O
3. You open a log file with `open(log_path, "a")`. What does mode `"a"` do?
CompTIA Data+ – scripting and automation
4. What is the primary reason to catch specific exception types (e.g., ValueError, FileNotFoundError) rather than a bare `except Exception`?
IBM Data Science – Python programming fundamentals
5. A for loop iterates over five CSV filenames. On the third file the validation function raises a ValueError. Using the error-handling pattern from this lesson, what happens to files four and five?
CompTIA Data+ – scripting and automation
6. Which of the following is a correct function definition that includes a docstring?
IBM Data Science – data wrangling and scripting
7. You introduce a wrong column name into one of the test CSV files. Which exception type would be most appropriate for your validate_value function to raise when the expected column is not found in a DataFrame row?
CompTIA Data+ – data governance and quality
8. A senior analyst reviews your batch script and says it violates data safety best practice. The most likely reason is that your script:
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.