0% found this document useful (0 votes)
2 views

Python Further Extensions

The document provides comprehensive notes on Python further extensions, covering topics such as virtual environments, pip usage, modular programming, object-oriented programming, file handling, exception handling, decorators, generators, context managers, and testing. Each section includes commands, examples, and explanations to enhance understanding and application. It serves as a guide for managing dependencies, structuring code, handling errors, and implementing advanced features in Python.

Uploaded by

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

Python Further Extensions

The document provides comprehensive notes on Python further extensions, covering topics such as virtual environments, pip usage, modular programming, object-oriented programming, file handling, exception handling, decorators, generators, context managers, and testing. Each section includes commands, examples, and explanations to enhance understanding and application. It serves as a guide for managing dependencies, structuring code, handling errors, and implementing advanced features in Python.

Uploaded by

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

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

You might also like