Advanced Topics
Section 5: Advanced Topics
Lesson 1: Exception Handling
1.1 Understanding Exceptions
Exceptions are events that occur during the execution of a program and disrupt the normal flow of code. Handling exceptions is crucial for gracefully managing errors and preventing program crashes.
Example:
# Understanding exceptions
try:
result = 10 / 0 # Attempting to divide by zero
except ZeroDivisionError as e:
print(f"Error: {e}")
# Output: Error: division by zero
1.2 Using try, except Blocks
The try and except blocks in Python allow you to catch and handle exceptions, preventing them from causing the program to terminate abruptly.
Example:
# Using try, except blocks
def divide_numbers(a, b):
try:
result = a / b
return result
except ZeroDivisionError as e:
print(f"Error: {e}")
return None
result1 = divide_numbers(10, 2) # Output: 5.0
result2 = divide_numbers(10, 0) # Output: Error: division by zero, result2 is None
Lesson 2: Regular Expressions
2.1 Pattern Matching Using Regular Expressions
Regular expressions (regex) are powerful tools for pattern matching in strings. They provide a concise and flexible way to search, match, and manipulate text.
Example:
# Pattern matching using regular expressions
import re
pattern = r"\b\d{3}-\d{2}-\d{4}\b" # Match social security numbers
text = "John's SSN is 123-45-6789 and Jane's is 987-65-4321."
matches = re.findall(pattern, text)
print(matches) # Output: ['123-45-6789', '987-65-4321']
Regular expression breakdown:
\b: Word boundary
\d: Digit
{3}: Exactly 3 occurrences
-: Hyphen
{2}: Exactly 2 occurrences
\d{4}: Exactly 4 digits
In Section 5, we explored advanced topics in Python, focusing on exception handling and regular expressions.
Exception handling is crucial for managing errors and preventing program crashes. The try and except blocks provide a mechanism to gracefully handle exceptions and continue the execution of a program.
Regular expressions offer a powerful way to perform pattern matching in strings. By defining specific patterns, you can search for, extract, or replace text efficiently. Mastering exception handling and regular expressions enhances your ability to write robust and flexible Python code, making your applications more resilient and capable of handling diverse scenarios.