Python Snippets
A collection of useful code snippets for Python.
decorator-example.py
# A decorator is a function that takes another function and
# extends its behavior without explicitly modifying it.
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_whee():
print("Whee!")
say_whee()flexible-functions-args-kwargs.py
# Use *args and **kwargs to accept a variable number of arguments.
def flexible_function(*args, **kwargs):
print("Positional arguments (*args):", args)
print("Keyword arguments (**kwargs):", kwargs)
# Example call
flexible_function(1, "hello", 3.14, name="CodeWebX", version=1.0)
# Output:
# Positional arguments (*args): (1, 'hello', 3.14)
# Keyword arguments (**kwargs): {'name': 'CodeWebX', 'version': 1.0}pythonic-looping-zip-enumerate.py
# Use enumerate to get both index and value
letters = ['a', 'b', 'c']
for index, value in enumerate(letters):
print(f"Index: {index}, Value: {value}")
# Use zip to iterate over multiple sequences at once
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")Page 1 of 2