Python Programming Labs

Master professional Python: regex, context managers, and asynchronous programming.

Professional Python Patterns - Module 6

Industry-level techniques for text processing, resource management, and concurrent code.

Lab 16: Regular Expressions
Expert
Coding Challenge
Your Task: Master regular expressions (regex) for powerful text pattern matching and manipulation using Python's re module.

Detailed Requirements:
1. Import re and use basic matching:
import re # Search for a pattern text = "My phone is 123-456-7890" match = re.search(r'\d{3}-\d{3}-\d{4}', text) if match: print(match.group()) # 123-456-7890

2. Common regex patterns:
\d - digit [0-9] \w - word char [a-zA-Z0-9_] \s - whitespace . - any character * - 0 or more + - 1 or more ? - 0 or 1 {n} - exactly n times [] - character class ^ - start of string $ - end of string

3. Find all matches:
text = "Email me at john@example.com or jane@test.org" emails = re.findall(r'\w+@\w+\.\w+', text) print(emails) # ['john@example.com', 'jane@test.org']

4. Search and replace:
text = "Hello World" result = re.sub(r'World', 'Python', text) print(result) # Hello Python

💡 Pro Tips:
• Use raw strings r'pattern' to avoid escape issues
• re.compile() for reusable patterns
• Groups with (): match.group(1)

Expected Output:
Phone: 123-456-7890 Emails: ['john@example.com', 'jane@test.org'] Replaced: Hello Python

Requirements Checklist

Import the re module
Use re.search() to find a pattern
Use re.findall() to find all matches
Use re.sub() for replacement
Use regex special characters (\d, \w, etc.)
Print the results
Output
# Click "Run Code" to execute your Python code
Hints & Tips
• Import: import re
• Search: re.search(r'pattern', text)
• Find all: re.findall(r'pattern', text)
• Replace: re.sub(r'old', 'new', text)
• Digits: \d+ Words: \w+
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 17: Context Managers
Expert
Coding Challenge
Your Task: Master context managers for safe resource handling using with statements and creating custom context managers.

Detailed Requirements:
1. Use with statement for file handling:
# with automatically closes the file, even if errors occur with open('file.txt', 'w') as f: f.write('Hello, World!') # File is automatically closed here with open('file.txt', 'r') as f: content = f.read() print(content)

2. Create a custom context manager (class-based):
class Timer: def __enter__(self): import time self.start = time.time() print("Timer started") return self def __exit__(self, exc_type, exc_val, exc_tb): elapsed = time.time() - self.start print(f"Elapsed: {elapsed:.4f} seconds") return False # Don't suppress exceptions with Timer() as t: # Code to time sum(range(1000000))

3. Create context manager with @contextmanager:
from contextlib import contextmanager @contextmanager def managed_resource(name): print(f"Acquiring {name}") try: yield name # Value returned to 'as' variable finally: print(f"Releasing {name}") with managed_resource("database") as r: print(f"Using {r}")

💡 Pro Tips:
• __enter__ runs at start of with block
• __exit__ runs at end (even if exception)
• Return False from __exit__ to propagate exceptions
• Use for: files, locks, database connections, temp changes

Expected Output:
Timer started Processing... Elapsed: 0.0234 seconds Acquiring database Using database Releasing database

Requirements Checklist

Use 'with' statement
Define __enter__ method
Define __exit__ method
Return self from __enter__
Use 'as' to capture context value
Print status messages
Output
# Click "Run Code" to execute your Python code
Hints & Tips
• Class needs: __enter__(self) and __exit__(self, ...)
• __enter__ returns value for 'as' variable
• __exit__ params: exc_type, exc_val, exc_tb
• Use: with MyContext() as ctx:
• Decorator: @contextmanager with yield
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 18: Async Programming
Expert
Coding Challenge
Your Task: Learn asynchronous programming with async/await for concurrent, non-blocking code execution.

Detailed Requirements:
1. Define an async function:
import asyncio async def greet(name): print(f"Hello, {name}!") await asyncio.sleep(1) # Non-blocking sleep print(f"Goodbye, {name}!") # Run async function asyncio.run(greet("Alice"))

2. Run multiple tasks concurrently:
async def fetch_data(id, delay): print(f"Fetching data {id}...") await asyncio.sleep(delay) print(f"Data {id} ready!") return f"Result {id}" async def main(): # Run tasks concurrently with gather results = await asyncio.gather( fetch_data(1, 2), fetch_data(2, 1), fetch_data(3, 1.5) ) print("All results:", results) asyncio.run(main())

3. Create tasks for more control:
async def main(): task1 = asyncio.create_task(fetch_data(1, 2)) task2 = asyncio.create_task(fetch_data(2, 1)) # Wait for both result1 = await task1 result2 = await task2 print(result1, result2)

💡 Pro Tips:
• async def defines a coroutine
• await pauses until the awaited task completes
• asyncio.gather() runs multiple coroutines concurrently
• Great for I/O-bound tasks (network, file operations)

Expected Output:
Fetching data 1... Fetching data 2... Fetching data 3... Data 2 ready! Data 3 ready! Data 1 ready! All results: ['Result 1', 'Result 2', 'Result 3']

Requirements Checklist

Import asyncio module
Define an async function
Use await keyword
Use asyncio.sleep()
Use asyncio.run() or asyncio.gather()
Print output from async functions
Output
# Click "Run Code" to execute your Python code
Hints & Tips
• Import: import asyncio
• Async function: async def func():
• Await: await asyncio.sleep(1)
• Run: asyncio.run(main())
• Concurrent: await asyncio.gather(task1, task2)
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below