0% found this document useful (0 votes)
5 views5 pages

Python Notes Set 2

The document covers essential Python programming concepts including file handling, exception handling, list comprehensions, lambda functions, and decorators. It provides examples for each topic, demonstrating how to open files, handle exceptions, create lists with comprehensions, use lambda functions with map and filter, and implement decorators. These concepts are fundamental for effective Python coding.

Uploaded by

fake786king
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views5 pages

Python Notes Set 2

The document covers essential Python programming concepts including file handling, exception handling, list comprehensions, lambda functions, and decorators. It provides examples for each topic, demonstrating how to open files, handle exceptions, create lists with comprehensions, use lambda functions with map and filter, and implement decorators. These concepts are fundamental for effective Python coding.

Uploaded by

fake786king
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

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()

You might also like