Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
Track GitHub Repository Growth in Python
A Python dashboard that fetches and displays GitHub repository statistics including stars, forks, creation date, and recent star activity using the GitHub API.
import requests
import json
from datetime import datetime, timedelta
def track_repo_growth(owner, repo):
url = f"https://api.github.com/repos/{owner}/{repo}"
headers = {"Accept": "application/vnd.github.v3+json"}
response = requests.get(url, headers=headers)
data = response.json()
name = data…
Build a Network Ping Monitor in Python
A Python script that continuously pings a remote host using subprocess and reports connectivity status with timestamps and latency.
import subprocess
import time
def ping_host(host, count=4):
"""Ping a host and return the results."""
try:
# Platform-independent ping command
cmd = ["ping", "-c", str(count), host]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
return result.stdout, r…
Find Dead Code in a Python Project Using AST
Walk a project tree, parse every Python file with ast, and list defined functions that are never called anywhere.
import ast
import os
import sys
def find_dead_code(project_path):
defined_functions = {}
called_functions = set()
for root, dirs, files in os.walk(project_path):
for file in files:
if file.endswith('.py'):
filepath = os.path.join(root, file)
with open(f…
Find Unused Python Packages Automatically
Scan a Python project's source files for imports and list installed packages not imported anywhere.
import pkg_resources
import ast
import os
import sys
from pathlib import Path
def find_imports_in_project(project_dir="."):
imports = set()
for py_file in Path(project_dir).rglob("*.py"):
try:
with open(py_file, "r") as f:
tree = ast.parse(f.read())
for node in …
Find Zombie Processes on Linux with Python
Parse the output of `ps -eo pid,stat,comm` to detect processes in zombie state (Z) on a Linux system and report their PIDs and commands.
#!/usr/bin/env python3
import os
import subprocess
def find_zombie_processes():
"""Find zombie processes (state 'Z') running on Linux."""
try:
result = subprocess.run(['ps', '-eo', 'pid,stat,comm'], capture_output=True, text=True, check=True)
zombies = []
for line in result.stdout.stri…
How to Generate Project Statistics Including Lines of Code and Complexity in Python
Walk through a Python script that scans a project directory for Python files, counts lines of code excluding blanks and comments, and estimates cyclomatic complexity by counting decision keywords.
import os
from pathlib import Path
def count_lines_of_code(filepath):
"""Counts lines of code in a Python file, excluding blank lines and comments."""
try:
with open(filepath, 'r') as f:
lines = f.readlines()
code_lines = [line for line in lines if line.strip() and not line.strip()…
How to Generate a Dependency Graph for Python Projects
This script walks through a Python project directory, parses each .py file's imports, and prints a dependency graph showing which modules depend on which other modules.
import os
import ast
from pathlib import Path
from collections import defaultdict
def get_imports(filepath):
with open(filepath) as f:
try:
tree = ast.parse(f.read())
except SyntaxError:
return []
imports = []
for node in ast.walk(tree):
if isinstance(node, …
How to Monitor Laptop Battery Health Over Time in Python
Log battery percentage, power status, and remaining time every N seconds to a JSON file using psutil for ongoing health monitoring.
import time
import json
from pathlib import Path
from datetime import datetime
try:
import psutil
except ImportError:
print("psutil required: pip install psutil")
exit(1)
LOG_FILE = Path("battery_health_log.json")
def monitor_battery(log_interval=60, duration=300):
"""Log battery percentage and rema…
How to check Python files for common coding mistakes
Walks a directory tree parsing each .py file with ast, reporting empty functions, bare try blocks, too many parameters, and empty classes.
import ast
import os
import sys
def check_file(filepath):
try:
with open(filepath) as f:
code = f.read()
tree = ast.parse(code, filename=filepath)
except SyntaxError as e:
print(f"{filepath}: SyntaxError: {e.msg}")
return
issues = []
for node in ast.wal…
Build a Python Performance Profiler That Generates Readable Reports
Use cProfile and pstats to profile Python functions and print a sorted performance report showing the top time-consuming calls.
import cProfile
import pstats
import io
from pathlib import Path
def slow_function():
total = 0
for i in range(500_000):
total += i ** 2
return total
def fast_function():
total = sum(i * i for i in range(500_000))
return total
def profile_functions():
profiler = cProfile.Profile()
…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.