Why Practice Matters More Than Theory
You've read the documentation. You've watched tutorials. You even understand what a try-except block does. But here's an uncomfortable truth about learning Python: understanding a concept and being able to apply it under pressure are two completely different skills.
This is especially true for three of the most practically important topics in intermediate-to-advanced Python: exception handling, file I/O, and regular expressions. These aren't academic exercises — they're the tools you'll reach for constantly when building real backend systems, whether you're validating API inputs in FastAPI, parsing log files, or processing user-uploaded data.
In this article, we'll walk through hands-on python practice exercises covering these three areas. Consider it a self-assessment: can you solve these, or do you need to revisit the fundamentals? Let's find out.
Python Exceptions Quiz: Can You Handle Failure Gracefully?
Error handling separates hobbyist code from production-ready applications. It's not enough to know that try/except exists — you need to know which exceptions to catch, when to use multiple except blocks, and how to design custom exceptions for your own applications.
Challenge 1: Catching the Right Exception
Consider this scenario: you're writing a function that reads a configuration file and parses a numeric value from it. What could go wrong?
- The file might not exist (FileNotFoundError)
- You might lack permission to read it (PermissionError)
- The value inside might not be a valid number (ValueError)
Your task: Write a function that handles all three scenarios with separate except blocks, each printing a distinct, helpful error message. This is a classic example of why lumping every error into a single generic except Exception: is considered bad practice — it hides the real problem from you and from whoever debugs your code later.
Challenge 2: Building a Custom Exception
Generic exceptions only get you so far. In real applications, you often need domain-specific errors. For example, imagine you're validating application configuration data and need to raise an error specifically when a required setting is missing.
Your task: Create a custom exception class called ConfigValidationError that inherits from Exception, then raise it inside a validation function when a key is missing from a settings dictionary. Bonus points if you include a custom message and additional attributes (like which key was missing) on the exception object itself.
Designing custom exceptions is a skill that pays off enormously once you start building APIs with FastAPI, where clear, structured error responses are essential for good developer experience.
Challenge 3: The finally Block Trap
Here's a tricky one: what happens when you have a return statement inside both your try block and your finally block? Many developers get surprised by the answer. Test yourself by writing a small function and predicting the output before running it — then verify your understanding.
File I/O Practice: Reading, Writing and Managing Paths
File handling might seem simple on the surface — open a file, read it, close it — but there's real nuance here that trips up even experienced developers, especially around modes, context managers, and text vs. binary data.
Challenge 4: Choosing the Correct File Mode
For each scenario below, identify the correct file mode:
- Appending new entries to a log file without erasing existing content
- Creating a new file but failing loudly if it already exists (to prevent overwrites)
- Reading and writing to the same file simultaneously
- Processing an image or audio file
If you're unsure about the difference between exclusive create mode and simple write mode, or between text mode and binary mode, this is a great signal to revisit the fundamentals before you accidentally overwrite production data.
Challenge 5: Context Managers in Action
Your task: Refactor the following (intentionally sloppy) code to use a context manager:
f = open('data.txt', 'r')
content = f.read()
f.close()
Using with open(...) as f: isn't just about writing fewer lines — it guarantees the file is properly closed even if an exception occurs mid-read. This is one of the most Pythonic patterns you'll use daily, and mastering it now will save you from subtle resource-leak bugs later.
Challenge 6: Build a Mini Log Analyzer
Here's a more substantial exercise that combines multiple skills: write a script that scans a log file, counts occurrences of warnings, errors, and exceptions, and outputs a structured JSON summary report. This kind of exercise mirrors real automation tasks you'll encounter in backend and DevOps work — and it's a great way to test your file reading methods (readline() vs. readlines()) alongside your data structuring skills.
Python Regex Practice: Pattern Matching Under Pressure
Regular expressions have a reputation for being intimidating — and honestly, that reputation is somewhat earned. But once the fundamentals click, regex becomes one of the most powerful tools in your text-processing toolkit.
Challenge 7: Extract All Digits
Given a messy string like "Order #4521 shipped on 03/15, tracking: 88291", write a regex pattern using Python's re module to extract every sequence of digits. This tests your understanding of the basic digit class and the difference between findall() and search().
Challenge 8: Quantifiers in Practice
Regex quantifiers — *, +, and ? — control how many times a pattern can repeat, and mixing them up is one of the most common beginner mistakes.
Your task: Write patterns that match:
- Words that are exactly three letters long
- Optional characters, such as matching both "color" and "colour"
- One or more vowels in a row within a word
If you can confidently explain the difference between * (zero or more) and + (one or more) without hesitating, you're in solid shape. If not, this is exactly the kind of gap that's worth closing before you rely on regex in a production data-parsing script.
Challenge 9: Real-World Text Extraction
Take a block of unstructured text (think: a customer support email or a log entry) and try to extract email addresses, phone numbers, or timestamps using regex. This exercise pushes you beyond toy examples and into the kind of messy, real-world data extraction you'll encounter when building automation tools or processing user input in a full stack application.
Bringing It All Together
Notice how these three topics — exceptions, file I/O, and regex — rarely exist in isolation in real projects. A well-built file-processing script needs solid exception handling for missing files, careful mode selection for reading, and often regex for extracting meaningful patterns from unstructured text. Building fluency in each of these areas individually is what allows you to combine them confidently when a real project demands it.
If you worked through these challenges and felt shaky on a few, that's completely normal — and it's exactly why structured, guided practice matters. In the FULL STACK PYTHON ARCHITECT: FAST API + REACT + VIBE CODING course, these exact topics are covered in depth, from advanced exception handling and custom exceptions, to file modes and context managers, to full regex pattern matching with the re module — all building toward practical, hands-on projects like log file analyzers and automated file organizers.
Featured Video
[Video embed placeholder: Watch the full walkthrough of exception handling, file I/O, and regex practice challenges from the course.]
Key Takeaways
- Exception handling isn't just about catching errors — it's about designing meaningful, specific error responses through multiple except blocks and custom exception classes.
- File I/O mastery means knowing your file modes cold, and always defaulting to context managers for safety.
- Regex becomes far less intimidating once you practice quantifiers and pattern extraction on real, messy data instead of toy examples.
- The real skill is combining these tools — as you'll do when building practical automation scripts like log analyzers or file organizers.
If these challenges exposed a few gaps in your Python foundation, don't worry — that's the entire point of practice. For a structured path through these topics and many more, including hands-on projects that tie everything together with FastAPI and React, explore the full Full Stack Python Architect course and keep building your skills one challenge at a time.