Python - Further Extensions
Python Further Extensions - Comprehensive Notes
1. Virtual Environments
Purpose: Manage project dependencies separately.
Command:
python -m venv myenv
Activate:
Windows: myenv\Scripts\activate
Mac/Linux: source myenv/bin/activate
Deactivate: deactivate
Install Packages:
pip install <package>
Freeze dependencies:
pip freeze > requirements.txt
2. Working with Pip
Install pip:
python -m ensurepip --upgrade
Upgrade pip:
pip install --upgrade pip
Install packages:
pip install <package-name>
Uninstall packages:
pip uninstall <package-name>
List installed packages:
pip list
3. Modular Programming
Why Modularize?: Increases readability, reusability, and organization.
Creating Modules:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
Importing Modules:
import mymodule
print(mymodule.greet("Alice"))
Selective Import:
from mymodule import greet
print(greet("Bob"))
4. Object-Oriented Programming (OOP)
Classes and Objects:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
return "Woof!"
dog1 = Dog("Buddy", "Golden Retriever")
print(dog1.bark())
Inheritance:
class Animal:
def speak(self):
return "I am an animal"
class Cat(Animal):
def speak(self):
return "Meow"
Encapsulation: Use underscores (_) for private variables.
Polymorphism: Different classes with the same method name.
5. File Handling
Reading a File:
with open('file.txt', 'r') as file:
contents = file.read()
Writing to a File:
with open('file.txt', 'w') as file:
file.write("Hello, World!")
Appending to a File:
with open('file.txt', 'a') as file:
file.write("More text\n")
6. Exception Handling
Try-Except:
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Multiple Exceptions:
try:
y = int("abc")
except (ValueError, TypeError):
print("Invalid input")
Finally Block:
try:
file = open("file.txt")
finally:
file.close()
7. Decorators
Purpose: Modify the behavior of functions or methods.
Basic Decorator:
def decorator_func(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator_func
def greet():
print("Hello!")
greet()
8. Generators and Iterators
Generators:
def my_generator():
for i in range(5):
yield i
for value in my_generator():
print(value)
Iterators:
my_list = [1, 2, 3]
iter_obj = iter(my_list)
print(next(iter_obj))
9. Context Managers
Usage: Manage resources like file handling automatically.
With Statement:
with open("file.txt", "r") as file:
contents = file.read()
Custom Context Manager:
class ManagedResource:
def __enter__(self):
print("Resource acquired")
def __exit__(self, exc_type, exc_value, traceback):
print("Resource released")
with ManagedResource():
print("Using resource")
10. Testing and Debugging
Unit Testing:
import unittest
def add(x, y):
return x + y
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
if __name__ == "__main__":
unittest.main()
Debugging:
import pdb
pdb.set_trace()