Docsity

python cheat sheet for beginners, Cheat Sheet of Electrical and Electronics Engineering

Toggle sidebar
bg1
labex.io
Python Cheatsheet
Essential syntax, structures, and patterns for modern Python development
This cheatsheet provides a quick reference to fundamental Python concepts, syntax, and advanced features, ideal for both beginners
and experienced developers.
Core Syntax
Operators, data types, variables
Functions & Control
Definitions, parameters, flow control
Data Structures
Lists, dicts, sets, tuples
Advanced Patterns
OOP, decorators, comprehensions
File & Package Management
I/O operations, virtual environments
Basics: Operators & Data Types
** > % // / * > - +
# 20 (multiplication before addition)
2 + 3 * 6
# 30 (parentheses override precedence)
(2 + 3) * 6
# 256 (exponentiation)
2 ** 8
Operator Precedence
Operators determine how values are combined. Precedence
dictates the order of operations.
# int (integer, whole number)
age = 25
# float (floating-point number, decimal)
price = 19.99
# str (string, sequence of characters)
name = "Alice"
# bool (boolean, True or False)
is_student = True
# list (ordered, mutable collection)
scores = [85, 92, 78]
# dict (dictionary, key-value pairs)
person = {'name': 'Bob'}
Core Data Types
Python's fundamental data types define the kind of values
variables can hold.
Functions: Definition & Lambda
Functions allow you to encapsulate reusable blocks of code.
# Define a function to print a greeting
def say_hello(name):
print(f'Hello {name}')
# Call the function with an argument
say_hello('Carlos')
# Functions can return values
def sum_two_numbers(a, b):
# Returns the sum
return a + b
# Lambda functions are small, anonymous functions for simple expressions.
# Defines a lambda function that takes x, y and returns their sum
add = lambda x, y: x + y
add(5, 3) # 8
Lists & Tuples
furniture = ['table', 'chair']
# 'table' (access item by index)
furniture[0]
# slice (get a sub-list)
furniture[1:3]
# Add item to end
furniture.append('bed')
# Remove specific item
furniture.remove('chair')
# Sort items in place
furniture.sort()
Lists (Mutable)
Lists are ordered collections of items that can be changed after
creation.
coords = (10, 20)
# 10 (access item by index)
coords[0]
# Cannot modify once created
# coords[0] = 15 # Error! (attempting to change an
immutable tuple)
Tuples (Immutable)
Tuples are ordered collections similar to lists, but they cannot be
changed after creation.
Dictionaries: Key-Value Pairs
Dictionaries store data in unordered key-value pairs, allowing efficient lookup by key.
my_cat = {
'size': 'fat',
'color': 'gray',
'disposition': 'loud'
}
# Add a new key-value pair or modify an existing one
my_cat['age_years'] = 2
# Iterate over key-value pairs in the dictionary
for key, value in my_cat.items():
print(f'{key}: {value}')
# Safe retrieval: Use .get() to avoid KeyError if the key doesn't exist, providing a default value instead.
my_cat.get('breed', 'unknown')
Sets: Unique Collections
Sets are unordered collections of unique items, useful for membership testing and eliminating duplicates.
# Directly create a set
s = {1, 2, 3}
# Convert a list to a set
s = set([1, 2, 3])
Create Sets
Sets can be created from a list or by directly listing elements.
s1 = {1, 2, 3}
s2 = {3, 4, 5}
# {1,2,3,4,5} (all unique elements from both sets)
s1.union(s2)
# {3} (elements common to both sets)
s1.intersection(s2)
# {1,2} (elements in s1 but not in s2)
s1.difference(s2)
Set Operations
Perform mathematical set operations like union, intersection,
and difference.
Control Flow
Control flow statements determine the order in which code instructions are executed.
if name == 'Debora':
# Executes if name is 'Debora'
print('Hi!')
elif name == 'George':
# Executes if name is 'George'
print('Hello!')
else:
# Executes if neither of the
above conditions are met
print('Who?')
1
Conditionals
Use `if`, `elif` (else if), and `else` for
decision-making logic.
pets = ['Bella', 'Milo']
# Loop through each item in the
'pets' list
for pet in pets:
print(pet)
2
For Loops
Iterate over a sequence (like a list, tuple,
or string) or other iterable objects.
count = 0
# Loop continues while count is
less than 5
while count < 5:
print('Hello')
# Increment count to eventually
stop the loop
count += 1
3
While Loops
Repeats a block of code as long as a
specified condition is true.
Comprehensions: Elegant Iteration
Comprehensions offer a concise way to create lists, sets, or dictionaries based on existing iterables.
# List comprehension: Creates a new list from an existing one, optionally with filtering.
names = ['Charles', 'Susan', 'Patrick']
# Creates ['Charles']
new_list = [n for n in names if n.startswith('C')]
# Set comprehension: Creates a new set, ensuring unique elements.
# {"ABC", "DEF"} (converts strings to uppercase)
{s.upper() for s in {"abc", "def"}}
# Dictionary comprehension: Creates a new dictionary from an iterable, often transforming key-value pairs.
c = {'name': 'Pooka', 'age': 5}
# Swaps keys and values: {'Pooka': 'name', 5: 'age'}
{v: k for k, v in c.items()}
String Formatting: Modern Approach
name = 'Elizabeth'
# Embeds variable directly
f'Hello {name}!'
a = 5
b = 10
# Embeds an expression
f'Sum is {a + b}'
F-Strings (Python 3.6+)
F-strings (formatted string literals) provide a readable and
efficient way to embed expressions inside string literals.
amount = 10000000
# '10,000,000' (add comma thousands separator)
f"{amount:,}"
pi = 3.1415926
# '3.14' (format to two decimal places)
f"{pi:.2f}"
Format Numbers
F-strings also allow for flexible number formatting.
String Manipulation
Python offers various methods to work with and modify strings.
# Slicing: Extracts parts of a string using start, end, and step indices.
spam = 'Hello world!'
# 'Hello' (characters from index 0 up to (but not including) 5)
spam[0:5]
# '!dlrow olleH' (reverses the string)
spam[::-1]
# String Methods: Common operations like changing case.
greet = 'Hello world!'
# 'HELLO WORLD!' (converts to uppercase)
greet.upper()
# 'hello world!' (converts to lowercase)
greet.lower()
# 'Hello World!' (capitalizes the first letter of each word)
greet.title()
# Join & Split: Combine or break apart strings based on delimiters.
# 'cats, rats' (joins elements of a list with a comma and space)
', '.join(['cats', 'rats'])
# ['My', 'name', 'is', 'Simon'] (splits string into a list of words)
'My name is Simon'.split()
Regular Expressions
Regular expressions (regex) are powerful tools for pattern matching and text parsing.
import re
# Compile pattern for better performance if used multiple times
phone_regex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
# Search for the pattern in a string
mo = phone_regex.search('My number is 415-555-4242.')
# '415-555-4242' (returns the matched string)
mo.group()
# Groups: Use parentheses in the regex to capture specific parts of the match.
phone_regex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
# '415' (first group)
mo.group(1)
# '555-4242' (second group)
mo.group(2)
# Find all: Returns a list of all non-overlapping matches.
# Returns a list of tuples for grouped matches
phone_regex.findall('Cell: 415-555-9999 Work: 212-555-0000')
Exception Handling
Handle runtime errors gracefully to prevent program crashes and provide meaningful feedback.
try:
# This will raise a ZeroDivisionError
result = 10 / 0
# Catch specific error type
except ZeroDivisionError:
print('Cannot divide by 0')
# Always executes, regardless of exception
finally:
print('Cleanup')
Try-Except
Use `try`, `except`, and `finally` blocks to catch and manage
exceptions.
# Inherit from base Exception class
class MyException(Exception):
pass
# Raise an instance of your custom exception
raise MyException('Custom error')
Custom Exceptions
Define your own exception classes for specific error conditions
in your application.
File Operations
Interact with the file system to read from or write to files.
# Read file: Open a file for reading and get its content. The 'with' statement ensures the file is closed automatically.
with open('file.txt') as f:
content = f.read()
# Read line by line: Iterate over each line in a file.
with open('file.txt') as f:
# 'end=' prevents extra newlines
for line in f:
print(line, end='')
# Write file: Open a file for writing. If the file exists, its content is truncated (deleted).
with open('output.txt', 'w') as f:
f.write('Hello world!\n')
# Append: Open a file for appending. New content is added to the end of the file.
with open('output.txt', 'a') as f:
f.write('Additional line')
Path Operations
The `pathlib` module offers an object-oriented approach to filesystem paths, making operations cleaner and more robust.
from pathlib import Path
# Path joining: Concatenate path components securely, handling separators automatically.
print(Path('usr') / 'bin' / 'spam')
# Current directory: Get the path to the current working directory.
Path.cwd()
# Create directories: Make new directories, optionally creating parent directories if they don't exist.
(Path.cwd() / 'new' / 'folder').mkdir(parents=True)
# Check existence: Verify if a path exists and if it's a file or directory.
# True if file exists
Path('file.py').exists()
# True if it's a file
Path('file.py').is_file()
# True if it's a directory
Path('/').is_dir()
Decorators: Enhance Functions
Decorators are a powerful way to modify or enhance functions or methods without changing their source code.
import functools # Used to preserve the original function's metadata
def your_decorator(func):
# Ensures wrapped function retains its original name, docstring, etc.
@functools.wraps(func)
# Wrapper function that will be executed instead of the original
def wrapper(*args, **kwargs):
# Code to execute before the original function
print("Before function")
# Call the original function
result = func(*args, **kwargs)
# Code to execute after the original function
print("After function")
return result
return wrapper
# Apply the decorator to the 'foo' function
@your_decorator
def foo():
print("Hello World!")
foo() # Calling foo() now runs the wrapper logic around it
# Expected output:
# Before function
# Hello World!
# After function
*Args & **Kwargs: Flexible Parameters
Use `*args` and `**kwargs` to allow functions to accept an arbitrary number of positional and keyword arguments, respectively.
def some_function(*args, **kwargs): # *args collects positional arguments into a tuple, **kwargs collects keyword
arguments into a dictionary
print(f'Arguments: {args}')
print(f'Keywords: {kwargs}')
some_function('arg1', 'arg2', key1='val1', key2='val2')
# Expected output:
# Arguments: ('arg1', 'arg2')
# Keywords: {'key1': 'val1', 'key2': 'val2'}
OOP: Core Concepts
Object-Oriented Programming (OOP) structures code using objects that contain data and methods. Key concepts include:
class MyClass:
def __init__(self):
# Convention for protected
member
self._protected = 10
# Name mangling for private
member
self.__private = 20
01
Encapsulation
Bundling data (attributes) and methods
that operate on the data within a single
unit (class). It restricts direct access to
some of an object's components.
class Animal: # Parent class
# Placeholder method
def speak(self): pass
class Dog(Animal): # Child class
inheriting from Animal
# Overrides parent's speak
method
def speak(self):
print("Woof!")
02
Inheritance
Allows a class (child/subclass) to inherit
attributes and methods from another class
(parent/superclass), promoting code
reusability.
class Shape: # Base class
def area(self): pass
class Rectangle(Shape): # Subclass
# Specific implementation of area
for Rectangle
def area(self):
return w * h
03
Polymorphism
Means "many forms." It allows objects of
different classes to be treated as objects of
a common base class, responding to the
same method call in different ways.
Dataclasses: Simplified Classes
Dataclasses provide a decorator to automatically generate common methods (`__init__`, `__repr__`, `__eq__`) for classes
primarily used to store data.
from dataclasses import dataclass
# Decorator to create a dataclass
@dataclass
class Number:
# Type-hinted field
val: int
obj = Number(2)
obj.val # 2
Basic Dataclass
Define data-holding classes with minimal boilerplate.
@dataclass
class Product:
name: str
# Field with default value
count: int = 0
# Another field with default
price: float = 0.0
# 'count' and 'price' use their defaults
obj = Product("Python")
obj.count # 0
With Defaults
Assign default values to fields directly in the class definition.
JSON & YAML
These are common data serialization formats for configuration files and data exchange.
import json
# Read: Load JSON data from a file into a Python object
(dictionary/list).
with open("data.json", "r") as f:
content = json.load(f)
# Write: Dump Python data (dictionary/list) to a JSON
formatted file.
data = {"name": "Joe", "age": 20}
with open("out.json", "w") as f:
# 'indent' makes the output human-readable
json.dump(data, f, indent=2)
JSON
JavaScript Object Notation (`json` module) is widely used for
web data.
from ruamel.yaml import YAML
# Initialize YAML parser
yaml = YAML()
with open("config.yaml") as f:
# Load YAML data from a file
data = yaml.load(f)
YAML
YAML Ain't Markup Language (`ruamel.yaml` is a common
library) is often used for configuration files due to its human-
friendly syntax.
Virtual Environments
Virtual environments isolate Python project dependencies, preventing conflicts between different projects.
# Install virtualenv
pip install virtualenv
# Create a new environment
mkvirtualenv HelloWorld
# Activate the environment
workon HelloWorld
# Deactivate the environment
deactivate
virtualenv
A tool to create isolated Python
environments.
# Install Poetry
pip install poetry
# Create a new project with a
virtual environment
poetry new my-project
# Add a dependency
poetry add pendulum
# Install dependencies
poetry install
Poetry
A dependency management and
packaging tool for Python.
# Install UV
curl -LsSf
https://astral.sh/uv/install.sh |
sh
# Initialize a project with UV
uv init my-project
# Add a package
uv add requests
# Run a script within the UV
environment
uv run python script.py
UV (Fast)
A modern, fast Python package
installer and resolver.
Main Entry Point
The `if __name__ == "__main__":` block ensures that certain code only runs when the script is executed directly, not when imported
as a module.
def add(a, b):
return a + b
if __name__ == "__main__":
# This code block will only execute when the script is run directly (e.g., python my_script.py)
# It will not run if this file is imported into another Python script.
result = add(3, 5)
print(result)
Built-in Functions: Quick Reference
Python provides a rich set of built-in functions for common tasks.
abs() - Returns the absolute value of a number.
all() - Returns True if all elements in an iterable are true.
any() - Returns True if any element in an iterable is true.
enumerate() - Adds a counter to an iterable, returning it as
an enumerate object.
filter() - Constructs an iterator from elements of an iterable
for which a function returns true.
len() - Returns the number of items in an object.
map() - Applies a given function to each item of an iterable
and returns a map object.
max() / min() - Returns the largest/smallest item in an
iterable or between two or more arguments.
range() - Generates an immutable sequence of numbers.
sorted() - Returns a new sorted list from the items in an
iterable.
sum() - Sums the items of an iterable.
zip() - Combines multiple iterables into a single iterator of
tuples.
# Examples of built-in functions
# 3 (length of the list)
len([1, 2, 3])
# 5 (maximum value in the list)
max([1, 5, 3])
# [1, 2, 3] (returns a new sorted list)
sorted([3, 1, 2])
# [(1, 'a'), (2, 'b')] (combines elements pairwise)
list(zip([1, 2], ['a', 'b']))
Debugging Essentials
Tools and techniques to identify and resolve issues in your code.
# Raise exception: Explicitly trigger an error.
raise Exception('Error message')
# Assertion: Verify a condition. If false, it raises an
AssertionError.
status = 'open'
# The message is shown if assertion fails
assert status == 'open', 'Must be open'
Exceptions & Assertions
Exceptions signal errors, while assertions check for conditions
that must be true at a certain point in code.
import logging
# Configure basic logging to show debug messages
logging.basicConfig(
# Set the logging level (DEBUG, INFO, WARNING,
ERROR, CRITICAL)
level=logging.DEBUG,
# Define output format
format='%(asctime)s - %(levelname)s - %(message)s'
)
# Log a debug message
logging.debug('Program started')
Logging
Logging provides a way to track events that happen when some
software runs, offering more flexibility than print statements for
debugging and monitoring.
Reference: This cheatsheet covers Python 3.6+ syntax and modern best practices for efficient development.
labex.io

Partial preview of the text

Download python cheat sheet for beginners and more Cheat Sheet Electrical and Electronics Engineering in PDF only on Docsity!

labex.io

Python Cheatsheet

Essential syntax, structures, and patterns for modern Python development

This cheatsheet provides a quick reference to fundamental Python concepts, syntax, and advanced features, ideal for both beginners and experienced developers.

Core Syntax

Operators, data types, variables

Functions & Control

Definitions, parameters, flow control

Data Structures

Lists, dicts, sets, tuples

Advanced Patterns

OOP, decorators, comprehensions

File & Package Management

I/O operations, virtual environments

Basics: Operators & Data Types

20 (multiplication before addition)

2 + 3 * 6

30 (parentheses override precedence)

(2 + 3) * 6

256 (exponentiation)

2 ** 8

Operator Precedence

Operators determine how values are combined. Precedence dictates the order of operations.

int (integer, whole number)

age = 25

float (floating-point number, decimal)

price = 19.

str (string, sequence of characters)

name = "Alice"

bool (boolean, True or False)

is_student = True

list (ordered, mutable collection)

scores = [85, 92, 78]

dict (dictionary, key-value pairs)

person = {'name': 'Bob'}

Core Data Types

Python's fundamental data types define the kind of values variables can hold.

Functions: Definition & Lambda

Functions allow you to encapsulate reusable blocks of code.

Define a function to print a greeting

def say_hello(name): print(f'Hello {name}')

Call the function with an argument

say_hello('Carlos')

Functions can return values

def sum_two_numbers(a, b):

Returns the sum

return a + b

Lambda functions are small, anonymous functions for simple expressions.

Defines a lambda function that takes x, y and returns their sum

add = lambda x, y: x + y add(5, 3) # 8

Lists & Tuples

furniture = ['table', 'chair']

'table' (access item by index)

furniture[0]

slice (get a sub-list)

furniture[1:3]

Add item to end

furniture.append('bed')

Remove specific item

furniture.remove('chair')

Sort items in place

furniture.sort()

Lists (Mutable)

Lists are ordered collections of items that can be changed after creation.

coords = (10, 20)

10 (access item by index)

coords[0]

Cannot modify once created

coords[0] = 15 # Error! (attempting to change an

immutable tuple)

Tuples (Immutable)

Tuples are ordered collections similar to lists, but they cannot be changed after creation.

Dictionaries: Key-Value Pairs

Dictionaries store data in unordered key-value pairs, allowing efficient lookup by key.

my_cat = { 'size': 'fat', 'color': 'gray', 'disposition': 'loud' }

Add a new key-value pair or modify an existing one

my_cat['age_years'] = 2

Iterate over key-value pairs in the dictionary

for key, value in my_cat.items(): print(f'{key}: {value}')

Safe retrieval: Use .get() to avoid KeyError if the key doesn't exist, providing a default value instead.

my_cat.get('breed', 'unknown')

Sets: Unique Collections

Sets are unordered collections of unique items, useful for membership testing and eliminating duplicates.

Directly create a set

s = {1, 2, 3}

Convert a list to a set

s = set([1, 2, 3])

Create Sets

Sets can be created from a list or by directly listing elements.

s1 = {1, 2, 3} s2 = {3, 4, 5}

{1,2,3,4,5} (all unique elements from both sets)

s1.union(s2)

{3} (elements common to both sets)

s1.intersection(s2)

{1,2} (elements in s1 but not in s2)

s1.difference(s2)

Set Operations

Perform mathematical set operations like union, intersection, and difference.

Control Flow

Control flow statements determine the order in which code instructions are executed.

if name == 'Debora':

Executes if name is 'Debora'

print('Hi!') elif name == 'George':

Executes if name is 'George'

print('Hello!') else:

Executes if neither of the

above conditions are met print('Who?')

Conditionals

Use if, elif (else if), and else for decision-making logic.

pets = ['Bella', 'Milo']

Loop through each item in the

'pets' list for pet in pets: print(pet)

For Loops

Iterate over a sequence (like a list, tuple, or string) or other iterable objects.

count = 0

Loop continues while count is

less than 5 while count < 5: print('Hello')

Increment count to eventually

stop the loop count += 1

While Loops

Repeats a block of code as long as a specified condition is true.

Comprehensions: Elegant Iteration

Comprehensions offer a concise way to create lists, sets, or dictionaries based on existing iterables.

List comprehension: Creates a new list from an existing one, optionally with filtering.

names = ['Charles', 'Susan', 'Patrick']

Creates ['Charles']

new_list = [n for n in names if n.startswith('C')]

Set comprehension: Creates a new set, ensuring unique elements.

{"ABC", "DEF"} (converts strings to uppercase)

{s.upper() for s in {"abc", "def"}}

Dictionary comprehension: Creates a new dictionary from an iterable, often transforming key-value pairs.

c = {'name': 'Pooka', 'age': 5}

Swaps keys and values: {'Pooka': 'name', 5: 'age'}

{v: k for k, v in c.items()}

String Formatting: Modern Approach

name = 'Elizabeth'

Embeds variable directly

f'Hello {name}!'

a = 5 b = 10

Embeds an expression

f'Sum is {a + b}'

F-Strings (Python 3.6+)

F-strings (formatted string literals) provide a readable and efficient way to embed expressions inside string literals.

amount = 10000000

'10,000,000' (add comma thousands separator)

f"{amount:,}"

pi = 3.

'3.14' (format to two decimal places)

f"{pi:.2f}"

Format Numbers

F-strings also allow for flexible number formatting.

String Manipulation

Python offers various methods to work with and modify strings.

Slicing: Extracts parts of a string using start, end, and step indices.

spam = 'Hello world!'

'Hello' (characters from index 0 up to (but not including) 5)

spam[0:5]

'!dlrow olleH' (reverses the string)

spam[::-1]

String Methods: Common operations like changing case.

greet = 'Hello world!'

'HELLO WORLD!' (converts to uppercase)

greet.upper()

'hello world!' (converts to lowercase)

greet.lower()

'Hello World!' (capitalizes the first letter of each word)

greet.title()

Join & Split: Combine or break apart strings based on delimiters.

'cats, rats' (joins elements of a list with a comma and space)

', '.join(['cats', 'rats'])

['My', 'name', 'is', 'Simon'] (splits string into a list of words)

'My name is Simon'.split()

Regular Expressions

Regular expressions (regex) are powerful tools for pattern matching and text parsing.

import re

Compile pattern for better performance if used multiple times

phone_regex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')

Search for the pattern in a string

mo = phone_regex.search('My number is 415-555-4242.')

'415-555-4242' (returns the matched string)

mo.group()

Groups: Use parentheses in the regex to capture specific parts of the match.

phone_regex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')

'415' (first group)

mo.group(1)

'555-4242' (second group)

mo.group(2)

Find all: Returns a list of all non-overlapping matches.

Returns a list of tuples for grouped matches

phone_regex.findall('Cell: 415-555-9999 Work: 212-555-0000')

Exception Handling

Handle runtime errors gracefully to prevent program crashes and provide meaningful feedback.

try:

This will raise a ZeroDivisionError

result = 10 / 0

Catch specific error type

except ZeroDivisionError: print('Cannot divide by 0')

Always executes, regardless of exception

finally: print('Cleanup')

Try-Except

Use try, except, and finally blocks to catch and manage exceptions.

Inherit from base Exception class

class MyException(Exception): pass

Raise an instance of your custom exception

raise MyException('Custom error')

Custom Exceptions

Define your own exception classes for specific error conditions in your application.

File Operations

Interact with the file system to read from or write to files.

Read file: Open a file for reading and get its content. The 'with' statement ensures the file is closed automatically.

with open('file.txt') as f: content = f.read()

Read line by line: Iterate over each line in a file.

with open('file.txt') as f:

'end=' prevents extra newlines

for line in f: print(line, end='')

Write file: Open a file for writing. If the file exists, its content is truncated (deleted).

with open('output.txt', 'w') as f: f.write('Hello world!\n')

Append: Open a file for appending. New content is added to the end of the file.

with open('output.txt', 'a') as f: f.write('Additional line')

Path Operations

The pathlib module offers an object-oriented approach to filesystem paths, making operations cleaner and more robust.

from pathlib import Path

Path joining: Concatenate path components securely, handling separators automatically.

print(Path('usr') / 'bin' / 'spam')

Current directory: Get the path to the current working directory.

Path.cwd()

Create directories: Make new directories, optionally creating parent directories if they don't exist.

(Path.cwd() / 'new' / 'folder').mkdir(parents=True)

Check existence: Verify if a path exists and if it's a file or directory.

True if file exists

Path('file.py').exists()

True if it's a file

Path('file.py').is_file()

True if it's a directory

Path('/').is_dir()

Decorators: Enhance Functions

Decorators are a powerful way to modify or enhance functions or methods without changing their source code.

import functools # Used to preserve the original function's metadata

def your_decorator(func):

Ensures wrapped function retains its original name, docstring, etc.

@functools.wraps(func)

Wrapper function that will be executed instead of the original

def wrapper(*args, **kwargs):

Code to execute before the original function

print("Before function")

Call the original function

result = func(*args, **kwargs)

Code to execute after the original function

print("After function") return result return wrapper

Apply the decorator to the 'foo' function

@your_decorator def foo(): print("Hello World!")

foo() # Calling foo() now runs the wrapper logic around it

Expected output:

Before function

Hello World!

After function

*Args & **Kwargs: Flexible Parameters

Use *args and **kwargs to allow functions to accept an arbitrary number of positional and keyword arguments, respectively.

def some_function(*args, **kwargs): # *args collects positional arguments into a tuple, **kwargs collects keyword arguments into a dictionary print(f'Arguments: {args}') print(f'Keywords: {kwargs}')

some_function('arg1', 'arg2', key1='val1', key2='val2')

Expected output:

Arguments: ('arg1', 'arg2')

Keywords: {'key1': 'val1', 'key2': 'val2'}

OOP: Core Concepts

Object-Oriented Programming (OOP) structures code using objects that contain data and methods. Key concepts include:

class MyClass: def init(self):

Convention for protected

member self._protected = 10

Name mangling for private

member self.__private = 20

Encapsulation

Bundling data (attributes) and methods that operate on the data within a single unit (class). It restricts direct access to some of an object's components.

class Animal: # Parent class

Placeholder method

def speak(self): pass

class Dog(Animal): # Child class inheriting from Animal

Overrides parent's speak

method def speak(self): print("Woof!")

Inheritance

Allows a class (child/subclass) to inherit attributes and methods from another class (parent/superclass), promoting code reusability.

class Shape: # Base class def area(self): pass

class Rectangle(Shape): # Subclass

Specific implementation of area

for Rectangle def area(self): return w * h

Polymorphism

Means "many forms." It allows objects of different classes to be treated as objects of a common base class, responding to the same method call in different ways.

Dataclasses: Simplified Classes

Dataclasses provide a decorator to automatically generate common methods (__init__, __repr__, __eq__) for classes primarily used to store data.

from dataclasses import dataclass

Decorator to create a dataclass

@dataclass class Number:

Type-hinted field

val: int

obj = Number(2) obj.val # 2

Basic Dataclass

Define data-holding classes with minimal boilerplate.

@dataclass class Product: name: str

Field with default value

count: int = 0

Another field with default

price: float = 0.

'count' and 'price' use their defaults

obj = Product("Python") obj.count # 0

With Defaults

Assign default values to fields directly in the class definition.

JSON & YAML

These are common data serialization formats for configuration files and data exchange.

import json

Read: Load JSON data from a file into a Python object

(dictionary/list). with open("data.json", "r") as f: content = json.load(f)

Write: Dump Python data (dictionary/list) to a JSON

formatted file. data = {"name": "Joe", "age": 20} with open("out.json", "w") as f:

'indent' makes the output human-readable

json.dump(data, f, indent=2)

JSON

JavaScript Object Notation (json module) is widely used for web data.

from ruamel.yaml import YAML

Initialize YAML parser

yaml = YAML() with open("config.yaml") as f:

Load YAML data from a file

data = yaml.load(f)

YAML

YAML Ain't Markup Language (ruamel.yaml is a common library) is often used for configuration files due to its human- friendly syntax.

Virtual Environments

Virtual environments isolate Python project dependencies, preventing conflicts between different projects.

Install virtualenv

pip install virtualenv

Create a new environment

mkvirtualenv HelloWorld

Activate the environment

workon HelloWorld

Deactivate the environment

deactivate

virtualenv

A tool to create isolated Python environments.

Install Poetry

pip install poetry

Create a new project with a

virtual environment poetry new my-project

Add a dependency

poetry add pendulum

Install dependencies

poetry install

Poetry

A dependency management and packaging tool for Python.

Install UV

curl -LsSf https://astral.sh/uv/install.sh | sh

Initialize a project with UV

uv init my-project

Add a package

uv add requests

Run a script within the UV

environment uv run python script.py

UV (Fast)

A modern, fast Python package installer and resolver.

Main Entry Point

The if __name__ == "__main__": block ensures that certain code only runs when the script is executed directly, not when imported as a module.

def add(a, b): return a + b

if name == "main":

This code block will only execute when the script is run directly (e.g., python my_script.py)

It will not run if this file is imported into another Python script.

result = add(3, 5) print(result)

Built-in Functions: Quick Reference

Python provides a rich set of built-in functions for common tasks.

abs() - Returns the absolute value of a number. all() - Returns True if all elements in an iterable are true. any() - Returns True if any element in an iterable is true. enumerate() - Adds a counter to an iterable, returning it as an enumerate object. filter() - Constructs an iterator from elements of an iterable for which a function returns true. len() - Returns the number of items in an object.

map() - Applies a given function to each item of an iterable and returns a map object. max() / min() - Returns the largest/smallest item in an iterable or between two or more arguments. range() - Generates an immutable sequence of numbers. sorted() - Returns a new sorted list from the items in an iterable. sum() - Sums the items of an iterable. zip() - Combines multiple iterables into a single iterator of tuples.

Examples of built-in functions

3 (length of the list)

len([1, 2, 3])

5 (maximum value in the list)

max([1, 5, 3])

[1, 2, 3] (returns a new sorted list)

sorted([3, 1, 2])

[(1, 'a'), (2, 'b')] (combines elements pairwise)

list(zip([1, 2], ['a', 'b']))

Debugging Essentials

Tools and techniques to identify and resolve issues in your code.

Raise exception: Explicitly trigger an error.

raise Exception('Error message')

Assertion: Verify a condition. If false, it raises an

AssertionError. status = 'open'

The message is shown if assertion fails

assert status == 'open', 'Must be open'

Exceptions & Assertions

Exceptions signal errors, while assertions check for conditions that must be true at a certain point in code.

import logging

Configure basic logging to show debug messages

logging.basicConfig(

Set the logging level (DEBUG, INFO, WARNING,

ERROR, CRITICAL) level=logging.DEBUG,

Define output format

format='%(asctime)s - %(levelname)s - %(message)s' )

Log a debug message

logging.debug('Program started')

Logging

Logging provides a way to track events that happen when some software runs, offering more flexibility than print statements for debugging and monitoring.

Reference: This cheatsheet covers Python 3.6+ syntax and modern best practices for efficient development.

labex.io