This tutorial is designed to take you an advanced level in Python programming. We will cover advanced topics with real-world examples, code snippets, and datasets. Each section will include problem-solving exercises and solutions.
Table of Contents
- Advanced Python
- Decorators and Generators
- Regular Expressions
- Working with APIs
- Multithreading and Multiprocessing
- Machine Learning with Scikit-Learn
3. Advanced Python
3.1 Decorators and Generators
- Decorators: Modify functions.
- Generators: Yield values lazily.
# Decorator Example
def my_decorator(func):
def wrapper():
print(“Before function call”)
func()
print(“After function call”)
return wrapper
@my_decorator
def say_hello():
print(“Hello!”)
say_hello()
# Generator Example
def my_generator():
yield 1
yield 2
yield 3
for value in my_generator():
print(value)
3.2 Regular Expressions
Used for pattern matching.
import re
text = “The rain in Spain”
result = re.search(“Spain”, text)
print(result.group())
3.3 Working with APIs
Fetch data from APIs using requests.
import requests
response = requests.get(“https://api.github.com”)
print(response.json())
3.4 Multithreading and Multiprocessing
- Multithreading: For I/O-bound tasks.
- Multiprocessing: For CPU-bound tasks.
# Multithreading Example
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
# Multiprocessing Example
import multiprocessing
def print_numbers():
for i in range(5):
print(i)
process = multiprocessing.Process(target=print_numbers)
process.start()
process.join()
3.5 Machine Learning with Scikit-Learn
Build a simple machine learning model.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
# Load dataset
iris = load_iris()
X, y = iris.data, iris.target
# Split dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# Train model
model = RandomForestClassifier()
model.fit(X_train, y_train)
# Predict
y_pred = model.predict(X_test)
print(“Accuracy:”, accuracy_score(y_test, y_pred))
Datasets
References