Cheatsheets

Python

Python

Python is an interpreted, high-level programming language known for its readability and simplicity. It supports multiple programming paradigms including procedural, object-oriented, and functional programming.

7 Categories 24 Sections 48 Examples
Python Programming Scripting Object-Oriented Functions Classes Variables Data Types Control Flow

Getting Started

Fundamental Python concepts and syntax for beginners.

Basic Syntax

Python fundamentals including print, variables, comments, and indentation.

Print statement and variables

Demonstrates variable assignment and f-string printing.

Code
name = "Python"
version = 3.12
print(f"Welcome to {name} {version}")
Execution
python -c "name = 'Python'; version = 3.12; print(f'Welcome to {name} {version}')"
Output
Welcome to Python 3.12
  • Python uses meaningful whitespace and indentation.
  • Variables are dynamically typed.

Comments and multiline strings

Shows different comment styles and how to write docstrings.

Code
# This is a single-line comment
"""
This is a multiline comment
or docstring
"""
message = "Hello" # inline comment
print(message)
Execution
python -c "message = 'Hello'; print(message)"
Output
Hello
  • Use '#' for single-line comments.
  • Use triple quotes for multiline comments or docstrings.

Data Types

Understanding Python's built-in data types and type conversion.

Type casting and checking

Shows type casting and how to check variable types.

Code
x = 42
y = float(x)
z = str(x)
print(type(x), type(y), type(z))
print(y, z)
Execution
python -c "x = 42; y = float(x); z = str(x); print(type(x), type(y), type(z)); print(y, z)"
Output
<class 'int'> <class 'float'> <class 'str'>
42.0 42
  • int(), float(), str(), bool() convert between types.
  • type() returns the data type of a variable.

None and boolean types

Demonstrates None, boolean types, and truthiness.

Code
a = None
b = True
c = False
print(type(a), type(b), type(c))
print(bool(1), bool(0), bool(""))
Execution
python -c "a = None; b = True; c = False; print(bool(1), bool(0), bool(''))"
Output
True False False
  • None represents a null value.
  • Empty sequences and 0 evaluate to False.

Numbers and Strings

Arithmetic operations, string slicing, and string methods.

Arithmetic operations and string slicing

Shows arithmetic operators and string slicing with start:end:step syntax.

Code
x = 10
y = 3
print(x + y, x - y, x * y, x / y, x // y, x % y, x ** y)
text = "Python"
print(text[0:3], text[-2:], text[::2])
Execution
python -c "x = 10; y = 3; print(x + y, x - y, x * y, x / y, x // y, x % y, x ** y); text = 'Python'; print(text[0:3], text[-2:], text[::2])"
Output
13 7 30 3.3333333333333335 3 1 1000
Pyt on Pto
  • / performs float division, // performs integer division.
  • Negative indices count from the end of the string.

String methods

Demonstrates common string methods like lower(), replace(), split(), and join().

Code
text = "HELLO WORLD"
print(text.lower())
print(text.replace("WORLD", "Python"))
print(text.split())
print("_".join(["a", "b", "c"]))
Execution
python -c "text = 'HELLO WORLD'; print(text.lower()); print(text.replace('WORLD', 'Python')); print(text.split()); print('_'.join(['a', 'b', 'c']))"
Output
hello world
HELLO Python
['HELLO', 'WORLD']
a_b_c
  • String methods are case-sensitive for the method call.
  • split() returns a list of strings.

Data Structures

Working with lists, tuples, dictionaries, and sets.

Lists

Creating and manipulating ordered, mutable sequences.

List creation and indexing

Demonstrates list creation, indexing, slicing, and the append() method.

Code
items = [1, 2, 3, 4, 5]
print(items[0], items[-1])
print(items[1:3], items[::2])
items.append(6)
print(items)
Execution
python -c "items = [1, 2, 3, 4, 5]; print(items[0], items[-1]); print(items[1:3], items[::2]); items.append(6); print(items)"
Output
1 5
[2, 3] [1, 3, 5]
[1, 2, 3, 4, 5, 6]
  • Lists are mutable and can be modified after creation.
  • Use negative indices to access from the end.

List methods and operations

Shows remove(), pop(), and extend() methods.

Code
items = [1, 2, 3, 2, 4]
items.remove(2)
print(items)
items.pop()
print(items)
items.extend([5, 6])
print(items)
Execution
python -c "items = [1, 2, 3, 2, 4]; items.remove(2); print(items); items.pop(); print(items); items.extend([5, 6]); print(items)"
Output
[1, 3, 2, 4]
[1, 3, 2]
[1, 3, 2, 5, 6]
  • remove() removes the first occurrence of a value.
  • pop() removes and returns the last element.
  • extend() adds multiple elements to the list.

Tuples

Immutable sequences and tuple unpacking.

Tuple creation and unpacking

Creates tuples and demonstrates unpacking values into variables.

Code
point = (10, 20)
x, y = point
print(f"x={x}, y={y}")
data = (1, 2, 3)
print(data[0], data[-1], len(data))
Execution
python -c "point = (10, 20); x, y = point; print(f'x={x}, y={y}'); data = (1, 2, 3); print(data[0], data[-1], len(data))"
Output
x=10, y=20
1 3 3
  • Tuples are immutable; they cannot be modified after creation.
  • Unpacking allows assigning tuple values to multiple variables.

Tuple operations

Demonstrates tuple concatenation and repetition.

Code
t1 = (1, 2)
t2 = (3, 4)
t3 = t1 + t2
print(t3)
print(t3 * 2)
print((5,) == (5))
Execution
python -c "t1 = (1, 2); t2 = (3, 4); t3 = t1 + t2; print(t3); print(t3 * 2); print((5,) == (5))"
Output
(1, 2, 3, 4)
(1, 2, 3, 4, 1, 2, 3, 4)
False
  • Use a trailing comma (5,) to create a single-element tuple.

Dictionaries

Key-value pairs and dictionary operations.

Dictionary creation and access

Shows dictionary creation and access using [] and get().

Code
person = {"name": "Alice", "age": 30, "city": "NYC"}
print(person["name"])
print(person.get("age"))
print(person.get("email", "Not found"))
Execution
python -c "person = {'name': 'Alice', 'age': 30, 'city': 'NYC'}; print(person['name']); print(person.get('age')); print(person.get('email', 'Not found'))"
Output
Alice
30
Not found
  • Use get() to safely access keys with a default value.
  • get() returns None if the key is not found and no default is provided.

Dictionary modification and iteration

Demonstrates adding, deleting, and iterating over dictionary entries.

Code
d = {"a": 1, "b": 2}
d["c"] = 3
del d["a"]
print(d)
print(d.keys(), d.values())
for key, value in d.items():
print(f"{key}: {value}")
Execution
python -c "d = {'a': 1, 'b': 2}; d['c'] = 3; del d['a']; print(d); print(list(d.keys()), list(d.values())); [(print(f'{k}: {v}')) for k, v in d.items()]"
Output
{'b': 2, 'c': 3}
dict_keys(['b', 'c']) dict_values([2, 3])
b: 2
c: 3
  • Use del to remove key-value pairs.
  • items() returns tuples of (key, value) pairs.

Sets

Unordered collections of unique elements.

Set creation and operations

Shows set creation (duplicates removed) and add/remove operations.

Code
s = {1, 2, 3, 3, 4}
print(s)
s.add(5)
s.remove(2)
print(s)
Execution
python -c "s = {1, 2, 3, 3, 4}; print(s); s.add(5); s.remove(2); print(s)"
Output
{1, 2, 3, 4}
{1, 3, 4, 5}
  • Sets automatically remove duplicates.
  • Sets are unordered, so iteration order is not guaranteed.

Set operations

Demonstrates union (|), intersection (&), and difference (-) operations.

Code
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # union
print(a & b) # intersection
print(a - b) # difference
Execution
python -c "a = {1, 2, 3}; b = {3, 4, 5}; print(a | b); print(a & b); print(a - b)"
Output
{1, 2, 3, 4, 5}
{3}
{1, 2}
  • Use pipes |, ampersand &, and minus - for set operations.

Control Flow

Conditionals, loops, and list comprehensions.

Conditionals

if/elif/else statements and logical operators.

if/elif/else statements

Shows if/elif/else conditional logic.

Code
x = 15
if x < 10:
print("Less than 10")
elif x < 20:
print("Between 10 and 20")
else:
print("20 or more")
Execution
python -c "x = 15; print('Between 10 and 20' if x >= 10 and x < 20 else ('Less than 10' if x < 10 else '20 or more'))"
Output
Between 10 and 20
  • Each conditional block must be indented.
  • Use elif for multiple conditions.

Comparison and logical operators

Demonstrates logical operators (and, or, not) and membership testing (in).

Code
x = 5
print(x > 3 and x < 10)
print(x == 5 or x == 10)
print(not (x == 0))
print(x in [1, 2, 5, 10])
Execution
python -c "x = 5; print(x > 3 and x < 10); print(x == 5 or x == 10); print(not (x == 0)); print(x in [1, 2, 5, 10])"
Output
True
True
True
True
  • Use 'and', 'or', 'not' for boolean operations.
  • Use 'in' to check membership in lists, strings, etc.

Loops

for and while loops with break and continue.

for loop with range and lists

Shows for loops iterating over ranges and lists.

Code
for i in range(3):
print(f"Iteration {i}")
for item in ["a", "b", "c"]:
print(item)
Execution
python -c "for i in range(3): print(f'Iteration {i}'); print('---'); [print(item) for item in ['a', 'b', 'c']]"
Output
Iteration 0
Iteration 1
Iteration 2
---
a
b
c
  • range(n) generates numbers from 0 to n-1.
  • for loops automatically iterate over sequences.

Loop control with break and continue

Demonstrates break (exit loop) and continue (skip iteration).

Code
for i in range(5):
if i == 2:
continue
if i == 4:
break
print(i)
Execution
python -c "for i in range(5):\n if i == 2:\n continue\n if i == 4:\n break\n print(i)"
Output
0
1
3
  • continue skips the current iteration.
  • break exits the loop entirely.

List Comprehensions

Concise syntax for creating and filtering lists.

Basic list comprehension

Shows list comprehension with transformation and filtering.

Code
squares = [x**2 for x in range(5)]
print(squares)
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
Execution
python -c "squares = [x**2 for x in range(5)]; print(squares); evens = [x for x in range(10) if x % 2 == 0]; print(evens)"
Output
[0, 1, 4, 9, 16]
[0, 2, 4, 6, 8]
  • List comprehensions are more concise than for loops.
  • Add if clause for filtering elements.

Nested list comprehension

Demonstrates nested list comprehensions and flattening matrices.

Code
matrix = [[i*j for j in range(3)] for i in range(3)]
print(matrix)
flat = [x for row in matrix for x in row]
print(flat)
Execution
python -c "matrix = [[i*j for j in range(3)] for i in range(3)]; print(matrix); flat = [x for row in matrix for x in row]; print(flat)"
Output
[[0, 0, 0], [0, 1, 2], [0, 2, 4]]
[0, 0, 0, 0, 1, 2, 0, 2, 4]
  • Nested comprehensions can be complex; prioritize readability.

Functions and Scope

Defining functions, arguments, and variable scope.

Function Definition

def keyword, parameters, return statements, and docstrings.

Basic function definition

Demonstrates basic function definition with parameters and return statement.

Code
def greet(name):
"""Greet a person by name."""
return f"Hello, {name}!"
print(greet("Alice"))
Execution
python -c "def greet(name):\n return f'Hello, {name}!'\nprint(greet('Alice'))"
Output
Hello, Alice!
  • Functions are defined with the def keyword.
  • Docstrings document function purpose and usage.

Function with default arguments

Shows functions with default parameter values.

Code
def add(a, b=0, c=0):
return a + b + c
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
Execution
python -c "def add(a, b=0, c=0):\n return a + b + c\nprint(add(1)); print(add(1, 2)); print(add(1, 2, 3))"
Output
1
3
6
  • Default parameters must come after required parameters.
  • Default values are evaluated once at function definition.

Arguments

Positional arguments, keyword arguments, *args, and **kwargs.

Positional and keyword arguments

Shows positional and keyword argument passing.

Code
def describe(name, age, city):
return f"{name} is {age} years old and lives in {city}"
print(describe("Alice", 30, "NYC"))
print(describe(name="Bob", city="LA", age=25))
Execution
python -c "def describe(name, age, city):\n return f'{name} is {age} years old and lives in {city}'\nprint(describe('Alice', 30, 'NYC')); print(describe(name='Bob', city='LA', age=25))"
Output
Alice is 30 years old and lives in NYC
Bob is 25 years old and lives in LA
  • Keyword arguments can be passed in any order.
  • Mix positional and keyword arguments by passing positional first.

Variable length arguments (*args and **kwargs)

Demonstrates *args for variable positional arguments and **kwargs for variable keyword arguments.

Code
def sum_numbers(*args):
return sum(args)
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print(sum_numbers(1, 2, 3, 4))
print_info(name="Alice", age=30, city="NYC")
Execution
python -c "def sum_numbers(*args):\n return sum(args)\ndef print_info(**kwargs):\n for key, value in kwargs.items():\n print(f'{key}: {value}')\nprint(sum_numbers(1, 2, 3, 4)); print_info(name='Alice', age=30, city='NYC')"
Output
10
name: Alice
age: 30
city: NYC
  • *args collects positional arguments as a tuple.
  • **kwargs collects keyword arguments as a dictionary.

Variable Scope

Local, global, and nonlocal variables.

Local and global scope

Shows local variables shadowing global variables.

Code
x = "global"
def func():
x = "local"
print(x)
func()
print(x)
Execution
python -c "x = 'global'\ndef func():\n x = 'local'\n print(x)\nfunc(); print(x)"
Output
local
global
  • Local variables are created when assigned in a function.
  • Accessing a global variable requires the global keyword to modify it.

Global and nonlocal keywords

Demonstrates global and nonlocal keywords to modify variables from enclosing scopes.

Code
x = 0
def outer():
y = 1
def inner():
nonlocal y
global x
x = 10
y = 2
inner()
print(f"y={y}")
outer()
print(f"x={x}")
Execution
python -c "x = 0\ndef outer():\n y = 1\n def inner():\n nonlocal y\n global x\n x = 10\n y = 2\n inner()\n print(f'y={y}')\nouter(); print(f'x={x}')"
Output
y=2
x=10
  • global allows modifying module-level variables.
  • nonlocal allows modifying variables in enclosing function scopes.

Object-Oriented Programming

Classes, inheritance, and special methods.

Classes

Class definition, __init__, self, and instance methods.

Basic class definition

Demonstrates class definition with __init__ constructor and instance methods.

Code
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says Woof!"
dog = Dog("Buddy", 3)
print(dog.bark())
Execution
python -c "class Dog:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n def bark(self):\n return f'{self.name} says Woof!'\ndog = Dog('Buddy', 3); print(dog.bark())"
Output
Buddy says Woof!
  • __init__ is the constructor called when creating an object.
  • self refers to the instance and must be the first parameter.

Instance attributes and methods

Shows instance attributes and methods that modify object state.

Code
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
return self.count
c = Counter()
print(c.increment())
print(c.increment())
print(c.count)
Execution
python -c "class Counter:\n def __init__(self):\n self.count = 0\n def increment(self):\n self.count += 1\n return self.count\nc = Counter(); print(c.increment()); print(c.increment()); print(c.count)"
Output
1
2
2
  • Instance attributes are created in __init__ or assigned later.
  • Methods can access and modify instance attributes.

Inheritance

Class inheritance, super(), and method overriding.

Class inheritance and super()

Shows class inheritance and method overriding.

Code
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
class Dog(Animal):
def speak(self):
return f"{self.name} barks"
dog = Dog("Rex")
print(dog.speak())
Execution
python -c "class Animal:\n def __init__(self, name):\n self.name = name\n def speak(self):\n return f'{self.name} makes a sound'\nclass Dog(Animal):\n def speak(self):\n return f'{self.name} barks'\ndog = Dog('Rex'); print(dog.speak())"
Output
Rex barks
  • Child classes inherit attributes and methods from parent classes.
  • Override methods by redefining them in the child class.

Using super() to call parent methods

Demonstrates super() to call parent class methods.

Code
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
dog = Dog("Buddy", "Golden")
print(f"{dog.name} is a {dog.breed}")
Execution
python -c "class Animal:\n def __init__(self, name):\n self.name = name\nclass Dog(Animal):\n def __init__(self, name, breed):\n super().__init__(name)\n self.breed = breed\ndog = Dog('Buddy', 'Golden'); print(f'{dog.name} is a {dog.breed}')"
Output
Buddy is a Golden
  • super() provides access to parent class methods.
  • Always call super().__init__() to initialize parent attributes.

Special Methods

__str__, __repr__, __len__, __getitem__, and other dunder methods.

__str__ and __repr__ methods

Shows __str__ for user-friendly representation and __repr__ for development.

Code
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
p = Point(3, 4)
print(str(p))
print(repr(p))
Execution
python -c "class Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n def __str__(self):\n return f'Point({self.x}, {self.y})'\np = Point(3, 4); print(str(p))"
Output
Point(3, 4)
  • __str__ returns a user-friendly string representation.
  • __repr__ returns a developer-friendly representation (ideally recreatable).

__len__ and __getitem__ methods

Demonstrates __len__ for len() and __getitem__ for indexing.

Code
class SimpleList:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
def __getitem__(self, index):
return self.items[index]
lst = SimpleList([1, 2, 3])
print(len(lst))
print(lst[0])
print(lst[-1])
Execution
python -c "class SimpleList:\n def __init__(self, items):\n self.items = items\n def __len__(self):\n return len(self.items)\n def __getitem__(self, index):\n return self.items[index]\nlst = SimpleList([1, 2, 3]); print(len(lst)); print(lst[0]); print(lst[-1])"
Output
3
1
3
  • __len__ enables len() function on custom objects.
  • __getitem__ enables indexing and slicing.

String Operations

Slicing, methods, formatting, and regular expressions.

String Slicing

String slicing with start:end:step and negative indexing.

String slicing with indices

Demonstrates string slicing with positive/negative indices and step values.

Code
s = "Python"
print(s[0:3])
print(s[3:])
print(s[-3:])
print(s[::2])
print(s[::-1])
Execution
python -c "s = 'Python'; print(s[0:3]); print(s[3:]); print(s[-3:]); print(s[::2]); print(s[::-1])"
Output
Pyt
hon
thon
Pto
nohtyP
  • s[start:end] slices from start to end-1.
  • Negative indices count from the end.
  • Step value (third parameter) allows skipping characters.

Advanced slicing techniques

Shows practical slicing use cases.

Code
s = "Hello World"
print(s[6:11])
print(s[-5:])
print(s[::3])
print(s[1::2])
Execution
python -c "s = 'Hello World'; print(s[6:11]); print(s[-5:]); print(s[::3]); print(s[1::2])"
Output
World
World
HloWrd
elo ol
  • Slicing is safe even with out-of-range indices.

String Methods

Methods like upper(), lower(), split(), join(), replace(), find(), strip().

Case conversion and whitespace handling

Shows case conversion and whitespace removal methods.

Code
s = " Hello World "
print(s.upper())
print(s.lower())
print(s.strip())
print(s.lstrip())
print(s.rstrip())
Execution
python -c "s = ' Hello World '; print(s.upper()); print(s.lower()); print(s.strip()); print(repr(s.lstrip())); print(repr(s.rstrip()))"
Output
HELLO WORLD
hello world
Hello World
'Hello World '
' Hello World'
  • strip() removes leading and trailing whitespace.
  • lstrip() and rstrip() remove from left and right only.

String splitting, joining, and replacement

Demonstrates split(), join(), replace(), and find() methods.

Code
text = "apple,banana,cherry"
items = text.split(",")
print(items)
print("-".join(items))
print(text.replace("apple", "orange"))
print(text.find("banana"))
Execution
python -c "text = 'apple,banana,cherry'; items = text.split(','); print(items); print('-'.join(items)); print(text.replace('apple', 'orange')); print(text.find('banana'))"
Output
['apple', 'banana', 'cherry']
apple-banana-cherry
orange,banana,cherry
6
  • split() returns a list of substrings.
  • join() concatenates list items with a separator.
  • find() returns the index of substring or -1 if not found.

String Formatting

f-strings, .format(), % formatting, and string interpolation.

f-strings and .format() method

Shows f-strings (modern) and .format() (older style) formatting.

Code
name = "Alice"
age = 30
city = "NYC"
print(f"Name: {name}, Age: {age}, City: {city}")
print("Name: {}, Age: {}, City: {}".format(name, age, city))
print("Name: {0}, Age: {1}, City: {2}".format(name, age, city))
Execution
python -c "name = 'Alice'; age = 30; city = 'NYC'; print(f'Name: {name}, Age: {age}, City: {city}')"
Output
Name: Alice, Age: 30, City: NYC
  • f-strings are preferred for their readability and performance.
  • .format() provides indexed and named placeholders.

Formatting numbers and expressions

Demonstrates formatting with precision, currency, and different bases.

Code
pi = 3.14159
price = 19.95
x = 10
print(f"Pi: {pi:.2f}")
print(f"Price: ${price:.2f}")
print(f"Expression: {x * 2}")
print(f"Hex: {x:x}")
Execution
python -c "pi = 3.14159; price = 19.95; x = 10; print(f'Pi: {pi:.2f}'); print(f'Price: ${price:.2f}'); print(f'Expression: {x * 2}'); print(f'Hex: {x:x}')"
Output
Pi: 3.14
Price: $19.95
Expression: 20
Hex: a
  • Use :f for float formatting with .2f for 2 decimal places.
  • f-strings support full Python expressions inside {}.

Regular Expressions

Pattern matching with re.match(), re.search(), re.sub(), re.compile().

Basic pattern matching

Shows match(), search(), and findall() for pattern matching.

Code
import re
text = "Hello 123"
print(re.match(r'\w+', text))
print(re.search(r'\d+', text))
print(re.findall(r'\w+', text))
Execution
python -c "import re; text = 'Hello 123'; m = re.match(r'\\w+', text); print(m.group() if m else None); m = re.search(r'\\d+', text); print(m.group() if m else None); print(re.findall(r'\\w+', text))"
Output
Hello
123
['Hello', '123']
  • match() checks at the beginning of the string.
  • search() finds the first match anywhere in the string.
  • findall() returns all matches as a list.

Pattern substitution and compilation

Demonstrates sub() for replacement and compile() for reusable patterns.

Code
import re
text = "The date is 2025-02-27"
print(re.sub(r'\d+', '#', text))
pattern = re.compile(r'[a-z]+')
print(pattern.findall("abc123def456"))
Execution
python -c "import re; text = 'The date is 2025-02-27'; print(re.sub(r'\\d+', '#', text)); pattern = re.compile(r'[a-z]+'); print(pattern.findall('abc123def456'))"
Output
The date is #-#-#
['abc', 'def']
  • sub() replaces matches with a replacement string.
  • compile() creates a pattern object for reuse.

File I/O and Advanced

File operations, context managers, exception handling, and higher-order functions.

File Operations

open(), read(), write(), readlines(), and seek().

Reading and writing files

Demonstrates writing to and reading from files.

Code
# Writing to a file
with open("example.txt", "w") as f:
f.write("Hello, Python!")
# Reading from a file
with open("example.txt", "r") as f:
content = f.read()
print(content)
Execution
python -c "with open('/tmp/example.txt', 'w') as f: f.write('Hello, Python!'); f = open('/tmp/example.txt', 'r'); content = f.read(); f.close(); print(content)"
Output
Hello, Python!
  • Use "w" mode for writing (overwrites existing file).
  • Use "r" mode for reading.
  • Always close files or use with statement.

Reading lines and file positioning

Shows readlines() for reading multiple lines.

Code
# Writing multiple lines
with open("lines.txt", "w") as f:
f.write("Line 1\nLine 2\nLine 3")
# Reading lines
with open("lines.txt", "r") as f:
lines = f.readlines()
for line in lines:
print(line.strip())
Execution
python -c "with open('/tmp/lines.txt', 'w') as f: f.write('Line 1\\nLine 2\\nLine 3'); f = open('/tmp/lines.txt', 'r'); lines = f.readlines(); f.close(); [print(line.strip()) for line in lines]"
Output
Line 1
Line 2
Line 3
  • readlines() returns a list of lines with newline characters.
  • strip() removes leading/trailing whitespace including newlines.

Context Managers

Using with statement for automatic resource management.

Context manager with open()

Shows how with statement automatically closes files.

Code
with open("data.txt", "w") as f:
f.write("Important data")
print(f.closed)
print(f.closed)
Execution
python -c "f = None; exec('with open(\\\"/tmp/data.txt\\\", \\\"w\\\") as f: f.write(\\\"Important data\\\"); print(f.closed)'); print(f.closed)"
Output
False
True
  • with statement ensures cleanup even if exceptions occur.
  • File is closed when exiting the with block.

Custom context manager

Demonstrates creating custom context managers with @contextmanager decorator.

Code
from contextlib import contextmanager
@contextmanager
def timer():
import time
start = time.time()
yield
print(f"Elapsed: {time.time() - start:.2f}s")
with timer():
sum(range(1000000))
Execution
python -c "from contextlib import contextmanager; import time\n@contextmanager\ndef timer():\n start = time.time()\n yield\n print(f'Elapsed: {time.time() - start:.2f}s')\nwith timer(): sum(range(1000000))"
Output
Elapsed: 0.01s
  • @contextmanager simplifies context manager creation.
  • Code before yield runs on entry, after yield on exit.

Exception Handling

try/except/else/finally blocks and raising exceptions.

try/except blocks

Shows try/except blocks for handling specific exceptions.

Code
try:
x = int("not a number")
except ValueError as e:
print(f"Error: {e}")
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Execution
python -c "try:\n x = int('not a number')\nexcept ValueError as e:\n print(f'Error: {e}'); try:\n result = 10 / 0\nexcept ZeroDivisionError:\n print('Cannot divide by zero')"
Output
Error: invalid literal for int() with base 10: 'not a number'
Cannot divide by zero
  • except block executes if the specific exception occurs.
  • Use 'as' to capture exception details.

try/except/else/finally

Demonstrates else (no exception) and finally (always executes) blocks.

Code
try:
x = 10 / 2
except ZeroDivisionError:
print("Error")
else:
print(f"Result: {x}")
finally:
print("Cleanup")
Execution
python -c "try:\n x = 10 / 2\nexcept ZeroDivisionError:\n print('Error')\nelse:\n print(f'Result: {x}')\nfinally:\n print('Cleanup')"
Output
Result: 5.0
Cleanup
  • else block executes if no exception occurs.
  • finally block always executes for cleanup.

Lambdas and Higher-Order Functions

Lambda functions, map(), filter(), sorted(), and functional programming.

Lambda functions and map()

Demonstrates lambda functions with map() for transformations.

Code
squares = list(map(lambda x: x**2, [1, 2, 3, 4]))
print(squares)
add = lambda x, y: x + y
print(add(5, 3))
Execution
python -c "squares = list(map(lambda x: x**2, [1, 2, 3, 4])); print(squares); add = lambda x, y: x + y; print(add(5, 3))"
Output
[1, 4, 9, 16]
8
  • lambda x: expression creates an anonymous function.
  • map() applies function to each element in a sequence.

filter() and sorted()

Shows filter() for selecting elements and sorted() with custom sort keys.

Code
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
data = [(3, "c"), (1, "a"), (2, "b")]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)
Execution
python -c "numbers = [1, 2, 3, 4, 5, 6]; evens = list(filter(lambda x: x % 2 == 0, numbers)); print(evens); data = [(3, 'c'), (1, 'a'), (2, 'b')]; sorted_data = sorted(data, key=lambda x: x[1]); print(sorted_data)"
Output
[2, 4, 6]
[(1, 'a'), (2, 'b'), (3, 'c')]
  • filter() keeps elements where the function returns True.
  • sorted(key=...) allows custom sorting with a function.