withopen('file.txt', 'r')as file: content = file.read()# File is automatically closed outside the block
34. Decorators
defmy_decorator(func):defwrapper():print("Something is happening before the function is called.")func()print("Something is happening after the function is called.")return wrapper@my_decoratordefsay_hello():print("Hello!")say_hello()
35. Asyncio (Asynchronous Programming)
import asyncioasyncdefmy_coroutine():print("Coroutine started.")await asyncio.sleep(1)print("Coroutine completed.")# Run the coroutineasyncio.run(my_coroutine())
36. Web Scraping with BeautifulSoup
from bs4 import BeautifulSoupimport requestsurl ="https://example.com"response = requests.get(url)soup =BeautifulSoup(response.text, 'html.parser')
37. Machine Learning with Scikit-Learn
from sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegression# Assuming X and y are your features and target variableX_train, X_test, y_train, y_test =train_test_split(X, y, test_size=0.2)model =LinearRegression()model.fit(X_train, y_train)
38. Django Web Framework
# Install DjangopipinstallDjango# Create a new Django projectdjango-adminstartprojectmyproject# Run the development serverpythonmanage.pyrunserver
39. Flask Web Framework
from flask import Flaskapp =Flask(__name__)@app.route('/')defhello_world():return'Hello, World!'