Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Build a Basic Text Processor in Python
Split text into sentences, count words, find the longest word, and convert text to uppercase — all with pure Python string methods.
text = """The quick brown fox jumps over the lazy dog.
Python is a powerful programming language.
Keep practicing every single day!"""
sentences = text.split(". ")
word_count = 0
longest_word = ""
for sentence in sentences:
words = sentence.split()
word_count += len(words)
for word in words:
clea…
How to Build a Text Processor in Python
This code defines functions to count words, sentences, and find the longest word in a text, then prints basic statistics like uppercase and lowercase versions.
def count_words(text):
return len(text.split())
def count_sentences(text):
sentence_endings = ".!?"
count = 0
for char in text:
if char in sentence_endings:
count += 1
return count
def longest_word(text):
words = text.split()
if not words:
return ""
retur…
How to Compare Two Strings in Python
Compares two string values and returns a detailed report with equality, case-insensitive comparison, lengths, and uppercase versions.
def compare_data(first_value, second_value):
"""Compare two string values and return a report."""
if first_value == second_value:
status = "MATCH"
else:
status = "DIFFER"
return {
"first_value": first_value,
"second_value": second_value,
"status": status,
…
How to Convert camelCase to snake_case in Python
Convert camelCase strings to snake_case using a simple Python function that inserts underscores before uppercase letters and lowercases everything.
def camel_to_snake(s):
result = ""
for i, char in enumerate(s):
if char.isupper() and i > 0:
result += "_"
result += char.lower()
return result
if __name__ == "__main__":
test_cases = ["camelCase", "helloWorld", "thisIsACoolExample", "already_snake", "UPPER"]
for case i…
How to Count Vowels in a String in Python
Counts uppercase and lowercase vowels in a given string using a set and a generator expression.
def count_vowels(text):
vowels = set("aeiouAEIOU")
return sum(1 for char in text if char in vowels)
if __name__ == "__main__":
sample = "Hello, World!"
result = count_vowels(sample)
print(f"Vowel count in '{sample}': {result}")
How to Generate Initials from a Full Name in Python
Extract and uppercase the first letter of each word in a full name to produce initials using standard string methods.
def generate_initials(full_name):
parts = full_name.strip().split()
initials = ''.join(part[0].upper() for part in parts if part)
return initials
if __name__ == "__main__":
name = "john f. kennedy"
print(generate_initials(name))
How to Swap Case of Every Character in Python
Swap uppercase to lowercase and lowercase to uppercase for every character in a string using Python's built-in swapcase() method.
def swap_case(text):
"""
Swap uppercase to lowercase and lowercase to uppercase
for every character in the given string.
"""
return text.swapcase()
if __name__ == "__main__":
sample = "Hello World! Python3.9"
result = swap_case(sample)
print(f"Input: {sample}")
print(f"Output: {r…
How to Process Text Lines with Lists and Loops in Python
This code processes a list of text lines by stripping whitespace, converting to uppercase, and reporting character counts per line and totals.
def process_text(lines):
"""Convert a list of text lines to uppercase and report line statistics."""
processed = []
total_chars = 0
for index, line in enumerate(lines, start=1):
cleaned = line.strip().upper()
processed.append(cleaned)
total_chars += len(cleaned)
pri…
How to Process Text into Words in Python
Splits a string into words, strips punctuation, and returns a list of uppercase words using a loop.
def convert_text_processor(text):
words = text.split()
processed = []
for word in words:
clean = word.strip('.,!?;:')
if len(clean) > 0:
processed.append(clean.upper())
return processed
if __name__ == "__main__":
sample_text = "Hello, world! This is a Python e…
How to Process Text with Lists and Loops in Python
Iterate over a list of text lines to count words, show uppercase versions, and report character counts per line.
# text_processor.py
def process_text(lines):
"""Count words, show uppercase, and count characters per line."""
total_words = 0
print("Line-by-line analysis:")
for i, line in enumerate(lines, start=1):
words = line.split()
total_words += len(words)
print(f" Line {i}: {len(words…
How to Use StrEnum with auto() in Python
Define string-valued enum members automatically by using StrEnum with the auto() helper, making each member's value its own uppercase name.
from enum import StrEnum, auto
class Color(StrEnum):
RED = auto()
GREEN = auto()
BLUE = auto()
class Language(StrEnum):
PYTHON = auto()
JAVASCRIPT = auto()
RUST = auto()
print(list(Color))
print(list(Language))
print(Color.RED == "RED")
print(Language.PYTHON == "PYTHON")
print(f"Color: {Co…
How to Map Strings to Uppercase in Python
Loops through a list of strings and builds a new list with each string converted to uppercase.
strings = ["hello", "world", "python", "skillset"]
uppercased = []
for s in strings:
uppercased.append(s.upper())
print(uppercased)
Generate Strong Random Passwords with Custom Rules in Python
Build a configurable password generator using Python's secrets module that lets you toggle lowercase, uppercase, digits, and punctuation.
import secrets
import string
def generate_password(length=16, use_lower=True, use_upper=True, use_digits=True, use_punct=True):
pool = ''
if use_lower:
pool += string.ascii_lowercase
if use_upper:
pool += string.ascii_uppercase
if use_digits:
pool += string.digits
if use_pu…
How to Build a CLI with argparse in Python
Create a beginner-friendly command-line tool in Python that processes multiple filenames with optional flags for verbose output and uppercase conversion.
import argparse
def main():
parser = argparse.ArgumentParser(
description="A simple CLI to process files with optional verbose mode."
)
parser.add_argument("filenames", nargs="+", help="Files to process")
parser.add_argument("-v", "--verbose", action="store_true", help="Print extra details")
…
How to Build a Simple Python CLI with argparse
Create a friendly command-line greeting tool with argparse that accepts a positional name and optional flags for custom greetings and uppercase output.
import argparse
def greet(name, greeting="Hello", uppercase=False):
message = f"{greeting}, {name}!"
return message.upper() if uppercase else message
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="A simple greeting tool to demonstrate argparse basics."
)
parser.…
How to Build a Simple argparse CLI in Python
Create a beginner-friendly command-line tool with argparse that reads a file, optionally uppercases its lines, and prints a configurable number of lines.
import argparse
def main():
parser = argparse.ArgumentParser(
description="Automate file processing with a simple CLI tool."
)
parser.add_argument("filename", help="Path to the input file")
parser.add_argument("--uppercase", action="store_true", help="Convert text to uppercase")
parser.add…
How to Build a Simple argparse CLI in Python
Build a beginner-friendly command-line tool with argparse that greets a user, with optional greeting text and uppercase output.
import argparse
def greet(name, greeting="Hello", uppercase=False):
message = f"{greeting}, {name}!"
if uppercase:
message = message.upper()
return message
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Simple CLI greeting tool")
parser.add_argument("name", help=…
How to Parse CLI Arguments in Python with argparse
Build a beginner-friendly CLI with argparse that accepts optional --name, --greeting, and --uppercase flags, then prints a customizable greeting.
import argparse
def main():
parser = argparse.ArgumentParser(description="Greet a user with optional customization.")
parser.add_argument("--name", default="world", help="Name to greet")
parser.add_argument("--greeting", default="Hello", help="Greeting word")
parser.add_argument("--uppercase", action=…
How to Test Properties with Random Inputs in Python
Write a simple property-based test in Python using random string generation to verify that string invariants like reverse-twice identity and uppercase idempotence always hold.
import random
import string
def generate_random_string(length: int) -> str:
"""Generate a random alphanumeric string of given length."""
chars = string.ascii_letters + string.digits
return "".join(random.choice(chars) for _ in range(length))
def reverse_twice_is_identity(s: str) -> bool:
"""Propert…
How to Build a Pipe and Filter Text Processing Chain in Python
A functional pipe-and-filter chain that transforms text through uppercase, whitespace normalization, number removal, stopword filtering, and file export.
import re
import sys
def pipe_filter_chain(stream):
def uppercase(text):
return text.upper()
def strip_whitespace(text):
return " ".join(text.split())
def remove_numbers(text):
return re.sub(r"\d+", "", text)
def remove_stopwords(text, stopwords={"the", "and", "of", "in"}):…
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.