Code Snippets

Python Code Snippets – ProjectPy
Filter by Category:
Showing 0 snippets

Read text file

File Operations
# This code reads a text file and prints its contents line by line.

file_path = 'example.txt'  # Specify the path to the text file

with open(file_path, 'r') as file:
    for line in file:
        print(line.strip())  # Print each line without leading/trailing whitespace

Write to file

File Operations
# This code writes a list of strings to a text file, one string per line.

file_path = 'output.txt'
lines_to_write = ['Line 1', 'Line 2', 'Line 3']

with open(file_path, 'w') as file:
    file.write('\n'.join(lines_to_write))

print(f"Data written to {file_path}")

Append to file

File Operations
# This code appends a line of text to a specified file in append mode.

file_path = 'example.txt'  # Specify the file path
line_to_append = 'This is a new line of text.\n'  # Text to append

with open(file_path, 'a') as file:  # Open the file in append mode
    file.write(line_to_append)  # Append the text to the file

Read CSV file

File Operations
import pandas as pd

# Read a CSV file and store it in a DataFrame
def read_csv_file(file_path):
    data_frame = pd.read_csv(file_path)
    return data_frame

# Example usage
if __name__ == "__main__":
    df = read_csv_file('data.csv')
    print(df.head())

Write CSV file

File Operations
import csv

# This code writes data to a CSV file named 'output.csv'.
data = [
    ['Name', 'Age', 'City'],
    ['Alice', 30, 'New York'],
    ['Bob', 25, 'Los Angeles'],
    ['Charlie', 35, 'Chicago']
]

with open('output.csv', mode='w', newline='') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerows(data)

Read JSON file

File Operations
import json

# This function reads a JSON file and returns its content as a Python dictionary
def read_json_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        data = json.load(file)
    return data

# Example usage:
# json_data = read_json_file('data.json')

Write JSON file

File Operations
import json

# This code writes a Python dictionary to a JSON file.
data = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

with open('data.json', 'w') as json_file:
    json.dump(data, json_file, indent=4)  # Write the dictionary to a JSON file with pretty formatting

List files in directory

File Operations
import os

# List all files in the specified directory
def list_files_in_directory(directory_path):
    try:
        return [file for file in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, file))]
    except FileNotFoundError:
        return f"Directory not found: {directory_path}"

# Example usage
if __name__ == "__main__":
    directory = '.'  # Current directory
    files = list_files_in_directory(directory)
    print(files)

Check if file exists

File Operations
import os

# Check if a specified file exists in the filesystem
def check_file_exists(file_path):
    return os.path.isfile(file_path)

# Example usage
file_path = 'example.txt'
if check_file_exists(file_path):
    print(f"The file '{file_path}' exists.")
else:
    print(f"The file '{file_path}' does not exist.")

Delete file

File Operations
import os

# Delete a specified file if it exists
def delete_file(file_path):
    try:
        if os.path.isfile(file_path):
            os.remove(file_path)
            print(f"File '{file_path}' has been deleted.")
        else:
            print(f"File '{file_path}' does not exist.")
    except Exception as e:
        print(f"Error deleting file: {e}")

# Example usage
# delete_file('path/to/your/file.txt')

Rename file

File Operations
import os

# Rename a file from 'old_filename.txt' to 'new_filename.txt'
old_filename = 'old_filename.txt'
new_filename = 'new_filename.txt'

try:
    os.rename(old_filename, new_filename)
    print(f'Renamed "{old_filename}" to "{new_filename}".')
except FileNotFoundError:
    print(f'Error: "{old_filename}" does not exist.')
except Exception as e:
    print(f'Error: {e}')

Get file size

File Operations
import os

# Get the size of a file in bytes
def get_file_size(file_path):
    try:
        return os.path.getsize(file_path)
    except FileNotFoundError:
        return "File not found."

# Example usage
file_path = 'example.txt'
size = get_file_size(file_path)
print(f"Size of '{file_path}': {size} bytes")

Copy file

File Operations
import shutil

# This function copies a file from the source path to the destination path
def copy_file(source_path, destination_path):
    try:
        shutil.copy2(source_path, destination_path)
        print(f"File copied from {source_path} to {destination_path}")
    except Exception as e:
        print(f"Error occurred: {e}")

# Example usage
copy_file('source.txt', 'destination.txt')

Move file

File Operations
import shutil
import os

# Move a file from source_path to destination_path
def move_file(source_path, destination_path):
    try:
        shutil.move(source_path, destination_path)
        print(f"File moved from {source_path} to {destination_path}")
    except FileNotFoundError:
        print(f"Error: The file {source_path} does not exist.")
    except Exception as e:
        print(f"An error occurred: {e}")

# Example usage
# move_file('path/to/source/file.txt', 'path/to/destination/file.txt')

Sort list

Data Processing
# This code sorts a list of numbers in ascending order and prints the result.

numbers = [34, 12, 5, 67, 23, 1]  # Example list of numbers
sorted_numbers = sorted(numbers)    # Sort the list using the built-in sorted function
print(sorted_numbers)               # Output the sorted list

Filter list

Data Processing
# This code filters a list of numbers, returning only even numbers.
def filter_even_numbers(numbers):
    return [num for num in numbers if num % 2 == 0]

# Example usage:
input_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter_even_numbers(input_numbers)
print(even_numbers)  # Output: [2, 4, 6, 8, 10]

Remove duplicates

Data Processing
# This code removes duplicates from a list while preserving the original order.
def remove_duplicates(input_list):
    seen = set()
    return [item for item in input_list if not (item in seen or seen.add(item))]

# Example usage
data = [1, 2, 2, 3, 4, 4, 5]
unique_data = remove_duplicates(data)
print(unique_data)  # Output: [1, 2, 3, 4, 5]

Merge dictionaries

Data Processing
# This code merges two dictionaries. If there are overlapping keys, 
# the values from the second dictionary will overwrite those from the first.

def merge_dictionaries(dict1, dict2):
    return {**dict1, **dict2}

# Example usage
dictionary_a = {'a': 1, 'b': 2}
dictionary_b = {'b': 3, 'c': 4}
merged_dictionary = merge_dictionaries(dictionary_a, dictionary_b)
print(merged_dictionary)  # Output: {'a': 1, 'b': 3, 'c': 4}

Flatten nested list

Data Processing
# This function flattens a nested list into a single list.
def flatten_nested_list(nested_list):
    flat_list = []
    for item in nested_list:
        if isinstance(item, list):
            flat_list.extend(flatten_nested_list(item))  # Recursive call for sublist
        else:
            flat_list.append(item)  # Append non-list items
    return flat_list

# Example usage:
nested = [1, [2, [3, 4], 5], 6]
flattened = flatten_nested_list(nested)
print(flattened)  # Output: [1, 2, 3, 4, 5, 6]

Group by key

Data Processing
# This code groups a list of dictionaries by a specified key and returns a dictionary of grouped items.

from collections import defaultdict

def group_by_key(data, key):
    grouped_data = defaultdict(list)
    for item in data:
        grouped_data[item[key]].append(item)
    return dict(grouped_data)

# Example usage
data = [
    {'category': 'fruit', 'name': 'apple'},
    {'category': 'fruit', 'name': 'banana'},
    {'category': 'vegetable', 'name': 'carrot'},
]

result = group_by_key(data, 'category')
print(result)

Count occurrences

Data Processing
# Count occurrences of each element in a list and return a dictionary of counts
def count_occurrences(elements):
    counts = {}
    for element in elements:
        counts[element] = counts.get(element, 0) + 1
    return counts

# Example usage
data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
result = count_occurrences(data)
print(result)  # Output: {'apple': 3, 'banana': 2, 'orange': 1}

Find min/max in list

Data Processing
# This code finds the minimum and maximum values in a given list of numbers.
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

minimum_value = min(numbers)
maximum_value = max(numbers)

print(f"Minimum value: {minimum_value}")
print(f"Maximum value: {maximum_value}")

Calculate average

Data Processing
# This function calculates the average of a list of numbers.
def calculate_average(numbers):
    if not numbers:
        return 0  # Return 0 for an empty list to avoid division by zero
    total_sum = sum(numbers)
    count = len(numbers)
    return total_sum / count

# Example usage
data = [10, 20, 30, 40, 50]
average = calculate_average(data)
print(f"The average is: {average}")

Parse date string

Data Processing
from datetime import datetime

# Parse a date string into a datetime object
def parse_date(date_string, date_format="%Y-%m-%d"):
    return datetime.strptime(date_string, date_format)

# Example usage
date_string = "2023-10-05"
parsed_date = parse_date(date_string)
print(parsed_date)  # Output: 2023-10-05 00:00:00

Reverse string

String Manipulation
# This function reverses a given string and returns the reversed version.
def reverse_string(input_string):
    return input_string[::-1]

# Example usage
original_string = "Hello, World!"
reversed_string = reverse_string(original_string)
print(reversed_string)  # Output: !dlroW ,olleH

Check palindrome

String Manipulation
# This function checks if a given string is a palindrome.
def is_palindrome(input_string):
    # Normalize the string by removing spaces and converting to lowercase
    normalized_string = ''.join(input_string.split()).lower()
    # Compare the string with its reverse
    return normalized_string == normalized_string[::-1]

# Example usage
result = is_palindrome("A man a plan a canal Panama")
print(result)  # Output: True

Remove whitespace

String Manipulation
# This code removes all types of whitespace from a given string.
def remove_whitespace(input_string):
    return ''.join(input_string.split())

# Example usage
original_string = "  Hello,   World!  This is  a test.  "
cleaned_string = remove_whitespace(original_string)
print(cleaned_string)  # Output: "Hello,World!Thisisatest."

Convert to title case

String Manipulation
# This function converts a given string to title case, where the first letter of each word is capitalized.

def convert_to_title_case(input_string):
    return input_string.title()

# Example usage
input_text = "hello world! this is a test."
title_cased_text = convert_to_title_case(input_text)
print(title_cased_text)  # Output: "Hello World! This Is A Test."

Count words

String Manipulation
# This function counts the number of words in a given string.
def count_words(text):
    # Split the text into words using whitespace as a delimiter and return the count
    return len(text.split())

# Example usage
sample_text = "Hello, world! This is a test."
word_count = count_words(sample_text)
print(f"Number of words: {word_count}")

Replace substring

String Manipulation
# This function replaces all occurrences of a substring within a string with a new substring.
def replace_substring(original_string, old_substring, new_substring):
    return original_string.replace(old_substring, new_substring)

# Example usage
if __name__ == "__main__":
    text = "Hello, world! Welcome to the world of Python."
    updated_text = replace_substring(text, "world", "universe")
    print(updated_text)  # Output: Hello, universe! Welcome to the universe of Python.

Split string by delimiter

String Manipulation
# This code splits a string into a list using a specified delimiter.
def split_string(input_string, delimiter):
    return input_string.split(delimiter)

# Example usage
my_string = "apple,banana,cherry"
result = split_string(my_string, ",")
print(result)  # Output: ['apple', 'banana', 'cherry']

Join list into string

String Manipulation
# This code joins a list of strings into a single string with a specified separator.
def join_list_to_string(string_list, separator=', '):
    return separator.join(string_list)

# Example usage
my_list = ['apple', 'banana', 'cherry']
result = join_list_to_string(my_list, ', ')
print(result)  # Output: apple, banana, cherry

Check string contains

String Manipulation
# This function checks if a given substring is present in the main string.

def contains_substring(main_string: str, substring: str) -> bool:
    return substring in main_string

# Example usage
text = "Hello, world!"
search_term = "world"
result = contains_substring(text, search_term)
print(f"Does the string contain '{search_term}'? {result}")

Extract numbers from string

String Manipulation
# Extracts all numbers from a given string and returns them as a list of integers.
import re

def extract_numbers(input_string):
    # Use regular expression to find all sequences of digits
    number_strings = re.findall(r'\d+', input_string)
    # Convert extracted strings to integers
    return [int(num) for num in number_strings]

# Example usage
result = extract_numbers("There are 3 apples, 7 oranges, and 10 bananas.")
print(result)  # Output: [3, 7, 10]

Basic HTTP request

Web Scraping
# This code performs a basic HTTP GET request to a specified URL and prints the response status and content.

import requests

url = 'https://example.com'  # Replace with the desired URL
response = requests.get(url)

print(f'Status Code: {response.status_code}')  # Print the HTTP status code
print('Response Content:', response.text[:200])  # Print the first 200 characters of the response content

Parse HTML with BeautifulSoup

Web Scraping
# This code snippet parses HTML content using BeautifulSoup to extract all the links (anchor tags)

from bs4 import BeautifulSoup
import requests

# Fetch the HTML content from a URL
response = requests.get('https://example.com')
html_content = response.text

# Parse the HTML with BeautifulSoup
soup = BeautifulSoup(html_content, 'html.parser')

# Extract all anchor tags and print their href attributes
links = [a['href'] for a in soup.find_all('a', href=True)]
print(links)

Extract all links

Web Scraping
# This script extracts all hyperlinks from a given webpage using BeautifulSoup and requests

import requests
from bs4 import BeautifulSoup

url = 'https://example.com'  # Replace with the target URL
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

links = [a['href'] for a in soup.find_all('a', href=True)]
print(links)

Download image from URL

Web Scraping
import requests

# This function downloads an image from a given URL and saves it to a specified file path.
def download_image(image_url, save_path):
    response = requests.get(image_url)
    if response.status_code == 200:
        with open(save_path, 'wb') as file:
            file.write(response.content)
        print(f"Image successfully downloaded: {save_path}")
    else:
        print(f"Failed to retrieve image. Status code: {response.status_code}")

# Example usage
download_image('https://example.com/image.jpg', 'downloaded_image.jpg')

Web scraping with headers

Web Scraping
# This script performs web scraping using requests with custom headers to mimic a browser.

import requests
from bs4 import BeautifulSoup

url = 'https://example.com'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}

response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')

# Extract and print the title of the webpage
page_title = soup.title.string
print(page_title)

Handle timeouts

Web Scraping
import requests
from requests.exceptions import Timeout

# This code snippet performs a web request with a timeout and handles potential timeout exceptions.
url = "https://example.com"

try:
    response = requests.get(url, timeout=5)  # Set timeout to 5 seconds
    response.raise_for_status()  # Raise an error for bad responses (4xx or 5xx)
    print("Response received:", response.text)
except Timeout:
    print("The request timed out. Please try again later.")
except requests.RequestException as e:
    print("An error occurred:", e)

Parse JSON API response

Web Scraping
import requests

# This function fetches and parses a JSON response from a given API URL
def fetch_and_parse_json(api_url):
    response = requests.get(api_url)
    response.raise_for_status()  # Raise an error for bad responses
    json_data = response.json()   # Parse the JSON response
    return json_data

# Example usage
api_url = 'https://api.example.com/data'
data = fetch_and_parse_json(api_url)
print(data)

POST request with data

Web Scraping
import requests

# This code sends a POST request with JSON data to a specified URL
url = "https://example.com/api/endpoint"
data = {
    "name": "John Doe",
    "email": "johndoe@example.com",
    "age": 30
}

response = requests.post(url, json=data)

# Check if the request was successful
if response.status_code == 200:
    print("Data posted successfully:", response.json())
else:
    print("Error occurred:", response.status_code, response.text)

GET request

APIs & Requests
import requests

# This code performs a GET request to a specified URL and prints the response JSON.
url = "https://api.example.com/data"  # Replace with the actual API endpoint
response = requests.get(url)

if response.status_code == 200:
    json_data = response.json()
    print(json_data)
else:
    print(f"Error: {response.status_code} - {response.text}")

POST request

APIs & Requests
import requests

# This code sends a POST request to the specified URL with JSON data and prints the response.
url = "https://example.com/api/resource"
data = {
    "name": "John Doe",
    "email": "john.doe@example.com"
}

response = requests.post(url, json=data)

if response.status_code == 201:
    print("Resource created successfully:", response.json())
else:
    print("Error:", response.status_code, response.text)

PUT request

APIs & Requests
import requests

# This code sends a PUT request to update a resource at the specified URL with JSON data.
url = "https://api.example.com/resource/1"
data = {
    "name": "Updated Resource",
    "description": "This resource has been updated."
}
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer your_access_token"
}

response = requests.put(url, json=data, headers=headers)

# Check the response status and print the result
if response.status_code == 200:
    print("Update successful:", response.json())
else:
    print("Update failed:", response.status_code, response.text)

Handle API errors

APIs & Requests
import requests

# Function to make a GET request and handle potential API errors
def fetch_data(api_url):
    try:
        response = requests.get(api_url)
        response.raise_for_status()  # Raise an error for bad responses (4xx or 5xx)
        return response.json()  # Return JSON data if successful
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
    except requests.exceptions.RequestException as req_err:
        print(f"Request error occurred: {req_err}")

# Example usage
data = fetch_data("https://api.example.com/data")

API with authentication

APIs & Requests
import requests

# This code snippet demonstrates how to make an authenticated API request using a Bearer token.
api_url = "https://api.example.com/data"
bearer_token = "YOUR_ACCESS_TOKEN"

headers = {
    "Authorization": f"Bearer {bearer_token}",
    "Content-Type": "application/json"
}

response = requests.get(api_url, headers=headers)

if response.status_code == 200:
    print("Data retrieved successfully:", response.json())
else:
    print("Failed to retrieve data:", response.status_code, response.text)

Rate limiting

APIs & Requests
import time
import requests

class RateLimiter:
    def __init__(self, max_requests, time_window):
        self.max_requests = max_requests
        self.time_window = time_window
        self.timestamps = []

    def allow_request(self):
        current_time = time.time()
        # Remove timestamps outside the time window
        self.timestamps = [t for t in self.timestamps if t > current_time - self.time_window]
        if len(self.timestamps) < self.max_requests:
            self.timestamps.append(current_time)
            return True
        return False

rate_limiter = RateLimiter(max_requests=5, time_window=60)

if rate_limiter.allow_request():
    response = requests.get("https://api.example.com/data")
    print(response.json())
else:
    print("Rate limit exceeded. Try again later.")

Retry failed requests

APIs & Requests
import requests
from time import sleep

def fetch_with_retries(url, retries=3, delay=2):
    """Fetch a URL with a specified number of retries on failure."""
    for attempt in range(retries):
        try:
            response = requests.get(url)
            response.raise_for_status()  # Raise an error for bad responses
            return response.json()  # Assuming the response is in JSON format
        except requests.RequestException as e:
            print(f"Attempt {attempt + 1} failed: {e}")
            sleep(delay)
    raise Exception("All retries failed.")

# Example usage
# data = fetch_with_retries("https://api.example.com/data")

Parse API response

APIs & Requests
import requests

# Fetches data from a given API endpoint and parses the JSON response.
def fetch_and_parse_api_response(api_url):
    response = requests.get(api_url)
    response.raise_for_status()  # Raise an error for bad responses
    data = response.json()  # Parse JSON response
    return data

# Example usage
api_url = 'https://api.example.com/data'
parsed_data = fetch_and_parse_api_response(api_url)
print(parsed_data)

SQLite connect and query

Database
# This code connects to an SQLite database, creates a table, and queries data from it.

import sqlite3

# Connect to SQLite database (creates it if it doesn't exist)
connection = sqlite3.connect('example.db')
cursor = connection.cursor()

# Create a sample table
cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)')
cursor.execute('INSERT INTO users (name) VALUES (?)', ('Alice',))
connection.commit()

# Query the data
cursor.execute('SELECT * FROM users')
for row in cursor.fetchall():
    print(row)

# Clean up
cursor.close()
connection.close()

Insert data to SQLite

Database
import sqlite3

# This code connects to an SQLite database and inserts a new record into a specified table.
def insert_data(database, table, data):
    with sqlite3.connect(database) as conn:
        cursor = conn.cursor()
        placeholders = ', '.join('?' * len(data))
        cursor.execute(f'INSERT INTO {table} VALUES ({placeholders})', data)
        conn.commit()

# Example usage
insert_data('example.db', 'users', ('John Doe', 30))

Update records

Database
import sqlite3

# Update a record in the database based on a given id
def update_record(db_path, record_id, new_value):
    with sqlite3.connect(db_path) as conn:
        cursor = conn.cursor()
        cursor.execute("UPDATE records SET value = ? WHERE id = ?", (new_value, record_id))
        conn.commit()

# Example usage
# update_record('database.db', 1, 'Updated Value')

Delete records

Database
import sqlite3

# Connect to the database and delete records based on a specified condition
def delete_records(database_path, table_name, condition):
    with sqlite3.connect(database_path) as conn:
        cursor = conn.cursor()
        sql_query = f"DELETE FROM {table_name} WHERE {condition}"
        cursor.execute(sql_query)
        conn.commit()
        print(f"Records deleted from {table_name} where {condition}")

# Example usage
# delete_records('example.db', 'users', 'age < 18')

Create table

Database
# This code snippet creates a SQLite database table named 'products' with three columns: id, name, and price.

import sqlite3

# Connect to the SQLite database (or create it if it doesn't exist)
connection = sqlite3.connect('example.db')
cursor = connection.cursor()

# Create the 'products' table
cursor.execute('''
CREATE TABLE IF NOT EXISTS products (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    price REAL NOT NULL
)
''')

# Commit changes and close the connection
connection.commit()
connection.close()

Fetch all rows

Database
import sqlite3

# Fetch all rows from a specified table in the SQLite database
def fetch_all_rows(database_path, table_name):
    connection = sqlite3.connect(database_path)
    cursor = connection.cursor()
    
    cursor.execute(f"SELECT * FROM {table_name}")
    rows = cursor.fetchall()
    
    connection.close()
    return rows

# Example usage
# rows = fetch_all_rows('example.db', 'users')

Parameterized query

Database
# This snippet demonstrates how to use a parameterized query to safely insert data into a SQLite database.

import sqlite3

# Connect to the SQLite database (or create it if it doesn't exist)
connection = sqlite3.connect('example.db')
cursor = connection.cursor()

# Create a table (if it doesn't exist)
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')

# Data to insert
user_name = 'Alice'
user_age = 30

# Use a parameterized query to insert the user data
cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', (user_name, user_age))

# Commit the changes and close the connection
connection.commit()
connection.close()

Check table exists

Database
import sqlite3

# Check if a table exists in the SQLite database
def check_table_exists(database_name, table_name):
    connection = sqlite3.connect(database_name)
    cursor = connection.cursor()
    cursor.execute(f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}';")
    exists = cursor.fetchone() is not None
    connection.close()
    return exists

# Example usage
if __name__ == "__main__":
    db_name = "example.db"
    table_name = "my_table"
    print(check_table_exists(db_name, table_name))

Get current date/time

DateTime
from datetime import datetime

# Get the current date and time
current_datetime = datetime.now()

# Format the date and time as a string
formatted_datetime = current_datetime.strftime('%Y-%m-%d %H:%M:%S')

print(f"Current Date and Time: {formatted_datetime}")

Format datetime

DateTime
from datetime import datetime

# This code formats the current datetime into a readable string format.
current_datetime = datetime.now()
formatted_datetime = current_datetime.strftime('%Y-%m-%d %H:%M:%S')

print(f"Current Date and Time: {formatted_datetime}")

Parse datetime string

DateTime
from datetime import datetime

# This function parses a datetime string into a datetime object.
def parse_datetime(datetime_string, format_string="%Y-%m-%d %H:%M:%S"):
    return datetime.strptime(datetime_string, format_string)

# Example usage
datetime_str = "2023-10-01 14:30:00"
parsed_datetime = parse_datetime(datetime_str)
print(parsed_datetime)  # Output: 2023-10-01 14:30:00

Calculate date difference

DateTime
from datetime import datetime

# Calculate the difference in days between two dates
def calculate_date_difference(date_str1, date_str2):
    date_format = "%Y-%m-%d"
    date1 = datetime.strptime(date_str1, date_format)
    date2 = datetime.strptime(date_str2, date_format)
    return (date2 - date1).days

# Example usage
date1 = "2023-01-01"
date2 = "2023-10-01"
print(calculate_date_difference(date1, date2))  # Output: 273

Add days to date

DateTime
from datetime import datetime, timedelta

# Adds a specified number of days to a given date and returns the new date.
def add_days_to_date(start_date: str, days_to_add: int) -> str:
    date_format = "%Y-%m-%d"
    initial_date = datetime.strptime(start_date, date_format)
    new_date = initial_date + timedelta(days=days_to_add)
    return new_date.strftime(date_format)

# Example usage
result_date = add_days_to_date("2023-10-01", 10)
print(result_date)  # Output: 2023-10-11

Get day of week

DateTime
from datetime import datetime

# This function returns the day of the week for a given date in 'YYYY-MM-DD' format
def get_day_of_week(date_string):
    date_object = datetime.strptime(date_string, '%Y-%m-%d')
    return date_object.strftime('%A')

# Example usage
date_input = '2023-10-01'
print(get_day_of_week(date_input))  # Output: Sunday

Convert timezone

DateTime
# This code converts a datetime object from one timezone to another using pytz.

from datetime import datetime
import pytz

# Define the original timezone and the target timezone
original_timezone = pytz.timezone('America/New_York')
target_timezone = pytz.timezone('Europe/London')

# Create a datetime object in the original timezone
original_time = original_timezone.localize(datetime(2023, 10, 1, 12, 0, 0))

# Convert to the target timezone
converted_time = original_time.astimezone(target_timezone)

print(f"Original Time: {original_time}")
print(f"Converted Time: {converted_time}")

Unix timestamp conversion

DateTime
import datetime

# Convert a Unix timestamp to a human-readable date and time
def convert_unix_timestamp(unix_timestamp):
    return datetime.datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')

# Example usage
timestamp = 1633036800  # Example Unix timestamp
formatted_date = convert_unix_timestamp(timestamp)
print(formatted_date)  # Output: 2021-10-01 00:00:00

Try-except basic

Error Handling
# This code attempts to divide two numbers and handles any division errors gracefully.

def safe_divide(numerator, denominator):
    try:
        result = numerator / denominator
    except ZeroDivisionError:
        return "Error: Cannot divide by zero."
    except TypeError:
        return "Error: Invalid input type. Please provide numbers."
    else:
        return f"Result: {result}"

# Example usage
print(safe_divide(10, 2))  # Valid division
print(safe_divide(10, 0))  # Division by zero
print(safe_divide(10, 'a'))  # Invalid type

Multiple exceptions

Error Handling
# This code demonstrates handling multiple exceptions while reading a file and converting its content to an integer.

filename = "data.txt"

try:
    with open(filename, 'r') as file:
        content = file.read()
        number = int(content)
        print(f"The number is: {number}")

except FileNotFoundError:
    print(f"Error: The file '{filename}' was not found.")
except ValueError:
    print("Error: The content of the file is not a valid integer.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

Custom exception

Error Handling
class CustomError(Exception):
    """Custom exception for handling specific errors in the application."""
    def __init__(self, message):
        super().__init__(message)
        self.message = message

def divide_numbers(numerator, denominator):
    """Divides two numbers and raises a CustomError for division by zero."""
    if denominator == 0:
        raise CustomError("Denominator cannot be zero.")
    return numerator / denominator

# Example usage
try:
    result = divide_numbers(10, 0)
except CustomError as e:
    print(e)

Finally block

Error Handling
# This code demonstrates the use of a finally block to ensure resource cleanup 
# regardless of whether an exception occurs or not.

try:
    file = open('example.txt', 'r')
    data = file.read()
    print(data)
except FileNotFoundError:
    print("File not found. Please check the file name.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
finally:
    if 'file' in locals():
        file.close()
        print("File has been closed.")

Context manager

Error Handling
import os
import tempfile

class TempFileContextManager:
    """Context manager for creating a temporary file that is deleted after use."""
    
    def __enter__(self):
        self.temp_file = tempfile.NamedTemporaryFile(delete=False)
        return self.temp_file.name

    def __exit__(self, exc_type, exc_value, traceback):
        os.remove(self.temp_file.name)

# Example usage
with TempFileContextManager() as temp_file_path:
    with open(temp_file_path, 'w') as temp_file:
        temp_file.write('Hello, World!')
    print(f'Temporary file created at: {temp_file_path}')

Raise exception

Error Handling
# This code demonstrates how to raise a custom exception with a specific message.

class CustomError(Exception):
    """A custom exception type for demonstration purposes."""
    pass

def process_value(value):
    if value < 0:
        raise CustomError("Value must be non-negative")
    return value * 2

try:
    result = process_value(-5)
except CustomError as e:
    print(f"Error occurred: {e}")

Exception logging

Error Handling
import logging

# Configure logging to log exceptions to a file
logging.basicConfig(filename='error.log', level=logging.ERROR)

def log_exception(exception):
    """Logs the given exception message to the error log."""
    logging.error("An exception occurred", exc_info=exception)

try:
    # Example operation that may raise an exception
    result = 10 / 0
except Exception as e:
    log_exception(e)

Simple decorator

Functions & Decorators
def simple_decorator(func):
    """A simple decorator that prints the function name before executing it."""
    def wrapper(*args, **kwargs):
        print(f"Calling function: {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@simple_decorator
def greet(name):
    """Greets the user with the provided name."""
    return f"Hello, {name}!"

# Example usage
print(greet("Alice"))

Decorator with arguments

Functions & Decorators
def repeat(num_times):
    """Decorator that repeats the execution of a function 'num_times'."""
    def decorator_repeat(func):
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                func(*args, **kwargs)
        return wrapper
    return decorator_repeat

@repeat(3)
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")

Timer decorator

Functions & Decorators
import time
from functools import wraps

def timer_decorator(func):
    """A decorator that times how long a function takes to execute."""
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} executed in {end_time - start_time:.4f} seconds")
        return result
    return wrapper

@timer_decorator
def example_function(n):
    """Example function that simulates a time-consuming task."""
    time.sleep(n)

example_function(2)

Memoization decorator

Functions & Decorators
def memoize(func):
    """Decorator to cache results of a function to optimize repeated calls with the same arguments."""
    cache = {}
    
    def wrapper(*args):
        if args not in cache:
            cache[args] = func(*args)
        return cache[args]
    
    return wrapper

@memoize
def fibonacci(n):
    """Return the nth Fibonacci number."""
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

# Example usage
print(fibonacci(10))  # Output: 55

Class decorator

Functions & Decorators
def class_decorator(cls):
    """A decorator that adds a greeting method to a class."""
    
    def greet(self):
        return f"Hello from {self.__class__.__name__}!"

    cls.greet = greet
    return cls

@class_decorator
class MyClass:
    pass

# Example usage
instance = MyClass()
print(instance.greet())  # Output: Hello from MyClass!

Property decorator

Functions & Decorators
class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        """Get the radius of the circle."""
        return self._radius

    @radius.setter
    def radius(self, value):
        """Set the radius of the circle, must be positive."""
        if value <= 0:
            raise ValueError("Radius must be positive.")
        self._radius = value

    @property
    def area(self):
        """Calculate the area of the circle."""
        return 3.14159 * (self._radius ** 2)

# Example usage
circle = Circle(5)
print(circle.area)  # Output: 78.53975
circle.radius = 10
print(circle.area)  # Output: 314.159

Simple class

Classes & OOP
# A simple class to represent a Rectangle with area calculation
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

# Example usage
rect = Rectangle(5, 10)
print(f"Rectangle area: {rect.area()}")

Class with inheritance

Classes & OOP
# This code demonstrates a simple class inheritance example with a base class and a derived class.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return "Some sound"

class Dog(Animal):
    def speak(self):
        return "Woof!"

# Example usage
dog = Dog("Buddy")
print(dog.name)  # Output: Buddy
print(dog.speak())  # Output: Woof!

Class properties

Classes & OOP
class Circle:
    def __init__(self, radius):
        self._radius = radius  # Private attribute

    @property
    def radius(self):
        """Get the radius of the circle."""
        return self._radius

    @radius.setter
    def radius(self, value):
        """Set the radius of the circle, must be positive."""
        if value > 0:
            self._radius = value
        else:
            raise ValueError("Radius must be positive.")

    @property
    def area(self):
        """Calculate the area of the circle."""
        import math
        return math.pi * (self._radius ** 2)

# Example usage:
circle = Circle(5)
print(circle.area)  # Output: Area of the circle
circle.radius = 10  # Set a new radius
print(circle.area)  # Output: Updated area of the circle

Static method

Classes & OOP
class MathUtils:
    """A utility class for mathematical operations with static methods."""

    @staticmethod
    def add(x, y):
        """Returns the sum of x and y."""
        return x + y

    @staticmethod
    def multiply(x, y):
        """Returns the product of x and y."""
        return x * y

# Example usage
sum_result = MathUtils.add(5, 3)
product_result = MathUtils.multiply(4, 2)
print(f"Sum: {sum_result}, Product: {product_result}")

Class method

Classes & OOP
class Circle:
    # A class to represent a circle with a method to calculate its area
    pi = 3.14159

    @classmethod
    def area(cls, radius):
        """Calculate the area of the circle given its radius."""
        return cls.pi * (radius ** 2)

# Example usage
if __name__ == "__main__":
    radius = 5
    print(f"Area of the circle with radius {radius} is: {Circle.area(radius)}")

Magic methods

Classes & OOP
class Vector:
    """A simple 2D vector class demonstrating magic methods."""
    
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

# Example usage
v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2
print(v3)  # Output: Vector(6, 8)
Scroll to Top
WhatsApp Chat on WhatsApp