Page 1: File Handling
- Open a file: open('filename.txt', 'r')
- Modes: 'r', 'w', 'a', 'b', 'x'
- Read: file.read(), file.readline(), file.readlines()
- Write: file.write("text")
Example:
with open('file.txt', 'w') as f:
f.write("Hello, File!")
Page 2: Exception Handling
Try-Except:
try:
x=1/0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This always executes")
- Use specific exceptions
- Use finally for cleanup
Page 3: List Comprehensions
- Shorter syntax for creating lists
squares = [x*x for x in range(10)]
evens = [x for x in range(10) if x % 2 == 0]
Nested:
matrix = [[i*j for j in range(3)] for i in range(3)]
Set and Dict Comprehensions:
s = {x for x in range(5)}
d = {x: x*x for x in range(5)}
Page 4: Lambda, Map, Filter, Reduce
Lambda:
- Anonymous functions
add = lambda x, y: x + y
Map:
nums = [1, 2, 3]
squares = list(map(lambda x: x*x, nums))
Filter:
evens = list(filter(lambda x: x%2==0, nums))
Reduce (from functools):
from functools import reduce
total = reduce(lambda x, y: x + y, nums)
Page 5: Decorators
- Functions that modify other functions
def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()