Examples
This page provides practical examples of using the documentation features.
Basic Examples
Hello World
The classic first program:
print("Hello, World!")
Working with Variables
# String variables
name = "Alice"
greeting = f"Hello, {name}!"
# Numeric variables
age = 30
height = 5.7
# Boolean variables
is_student = False
has_license = True
Data Structures
Lists
# Creating lists
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
# List operations
fruits.append("grape")
fruits.remove("banana")
first_fruit = fruits[0]
# List comprehension
squares = [x**2 for x in range(10)]
Dictionaries
# Creating dictionaries
person = {
"name": "Bob",
"age": 25,
"city": "New York"
}
# Dictionary operations
person["email"] = "bob@example.com"
age = person.get("age", 0)
# Iterating over dictionaries
for key, value in person.items():
print(f"{key}: {value}")
Functions and Classes
Function Examples
def calculate_area(radius):
"""Calculate the area of a circle."""
import math
return math.pi * radius ** 2
def greet(name, title="Mr."):
"""Greet a person with optional title."""
return f"Hello, {title} {name}!"
# Using functions
area = calculate_area(5)
greeting = greet("Smith", title="Dr.")
Class Examples
class Person:
"""Represent a person."""
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
"""Introduce the person."""
return f"Hi, I'm {self.name}, {self.age} years old."
def have_birthday(self):
"""Increment age by one."""
self.age += 1
return f"Happy birthday! Now {self.age} years old."
# Using the class
person = Person("Alice", 30)
print(person.introduce())
print(person.have_birthday())
File Operations
Reading Files
# Reading entire file
with open("data.txt", "r") as file:
content = file.read()
print(content)
# Reading line by line
with open("data.txt", "r") as file:
for line in file:
print(line.strip())
Writing Files
# Writing text to file
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a test.\n")
# Appending to file
with open("output.txt", "a") as file:
file.write("Additional line.\n")
Error Handling
Try-Except Blocks
def divide(a, b):
"""Safely divide two numbers."""
try:
result = a / b
return result
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
return None
except TypeError:
print("Error: Invalid input types!")
return None
finally:
print("Division operation completed.")
# Usage
result = divide(10, 2) # Returns 5.0
result = divide(10, 0) # Prints error message
Custom Exceptions
class ValidationError(Exception):
"""Custom validation exception."""
pass
def validate_age(age):
"""Validate age input."""
if not isinstance(age, int):
raise ValidationError("Age must be an integer")
if age < 0:
raise ValidationError("Age cannot be negative")
if age > 150:
raise ValidationError("Age seems unrealistic")
return True
# Usage
try:
validate_age(25) # Valid
validate_age(-5) # Raises ValidationError
except ValidationError as e:
print(f"Validation failed: {e}")
Advanced Examples
Decorators
import time
import functools
def timer(func):
"""Decorator to measure function execution time."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.4f} seconds")
return result
return wrapper
@timer
def slow_function():
"""A function that takes some time."""
time.sleep(1)
return "Done!"
# Usage
result = slow_function() # Prints execution time
Context Managers
class DatabaseConnection:
"""Context manager for database connections."""
def __enter__(self):
print("Opening database connection...")
self.connection = "Connected"
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Closing database connection...")
self.connection = None
def query(self, sql):
"""Execute a query."""
return f"Executing: {sql}"
# Usage
with DatabaseConnection() as db:
result = db.query("SELECT * FROM users")
print(result)
See Also
Getting Started - Basic setup and configuration
API Reference - Detailed API documentation
FAQ - Frequently Asked Questions - Frequently asked questions