Python is one of the most popular and beginner-friendly programming languages in the world. Whether you’re building websites, analyzing data, automating tasks, or diving into machine learning, Python is everywhere — and for good reason. Its clean syntax and vast ecosystem make it a go-to choice for developers of all levels.
But with so many functions, libraries, and syntax rules, it’s not always easy to remember everything. That’s where a Python Cheat Sheet comes in handy. It’s a compact, easy-to-scan reference guide designed to help you code faster, avoid repetitive Googling, and boost your overall productivity.
let’s start
Python Basics
Variables and Data Types
In Python, variables are used to store data. You don’t need to declare the type explicitly — Python automatically determines the data type at runtime. This is known as dynamic typing. Understanding how variables and data types work is the first step to writing effective Python code.
Python supports several core data types, including:
- Integers for whole numbers
- Floats for decimal numbers
- Strings for text
- Booleans for logical values (True/False)
You can also convert between these types when needed, and check the type of any variable using built-in functions.
Here’s a quick overview of variable assignment, type conversion, and type checking in Python:
Variable Assignment
Common Data Types
int
→ Whole numbers like5
,-3
,100
float
→ Decimal numbers like3.14
,0.5
,-1.0
str
→ Strings of text like"hello"
or'world'
bool
→ Boolean values:True
orFalse
Type Conversion
You can convert between types using built-in functions:
Type Checking
Use the type()
function to check a variable’s type:
Operators
Operators in Python are special symbols or keywords used to perform operations on variables and values. Understanding operators is crucial for writing logical and efficient code. Python supports several types of operators, each serving a specific purpose — from math operations to comparisons and logical checks.
Below is a breakdown of the most commonly used operator types in Python:
Arithmetic Operators
Used to perform basic mathematical operations:
Comparison Operators
Used to compare two values and return a boolean (True
or False
):
Logical Operators
Used to combine multiple conditions:
Assignment Operators
Used to assign and update the value of a variable:
Membership Operators
Used to check if a value exists in a sequence (like list, string, etc.):
Identity Operators
Used to check if two variables refer to the same object in memory:
Comments
Comments are lines in your code that are ignored by the Python interpreter. They’re useful for explaining your logic, making notes, or temporarily disabling parts of code. Well-written comments improve code readability and maintainability.
Python supports two main types of comments:
Single-line Comments
Use the #
symbol to add a comment on a single line. Everything after the #
is ignored by Python.
Multi-line Comments
There is no official multi-line comment syntax in Python, but you can simulate it using triple quotes ('''
or """
). These are technically multi-line strings, but if they’re not assigned to a variable, they’re ignored — effectively acting as comments.
String Operations
String Basics
Strings are one of the most commonly used data types in Python. They are sequences of characters enclosed in either single quotes (' '
) or double quotes (" "
). Python also supports multi-line strings using triple quotes.
Understanding how to create, access, and manipulate strings is essential for text processing and data handling.
Creating Strings
String Indexing and Slicing
Strings are zero-indexed, meaning the first character has index 0
. You can access individual characters or extract parts of the string using slicing.
String Concatenation
You can combine (concatenate) strings using the +
operator, and repeat them using the *
operator.
String Methods
Python provides many built-in methods to work with strings efficiently. These methods allow you to manipulate, format, and analyze string data with ease. Below is a quick reference to the most commonly used string methods:
Case Conversion Methods
Whitespace Removal Methods
Splitting and Joining
Replace, Find, and Count
Start/End Checks
Character Checks
These methods return True
or False
based on string content:
String Formatting
String formatting allows you to insert variables or values into strings in a readable and structured way. Python offers several methods for formatting strings — from modern f-strings to older techniques like .format()
and %
formatting.
f-Strings (Python 3.6+)
The most modern and preferred way to format strings. Use the f
prefix and insert variables inside {}
.
You can also use expressions inside {}
:
.format()
Method
Useful for inserting multiple values using placeholders {}
:
%
Formatting (Old Style)
An older formatting style, similar to C-style strings:
Common format specifiers:
%s
– string%d
– integer%f
– float
You can also control decimal places:
Multi-line Strings
Triple quotes allow you to write strings across multiple lines:
These are also commonly used for documentation strings (docstrings) in functions and classes.
Data Structures
Lists
Lists are ordered, mutable (changeable) collections in Python. They can hold items of any data type and are commonly used to store sequences of elements like numbers, strings, or even other lists.
Creating Lists
You can create a list using square brackets []
or the list()
constructor:
List Indexing and Slicing
Lists are zero-indexed. Use indexing to access individual elements and slicing to access sublists.
Common List Methods
List Comprehensions
A concise way to create new lists by applying an expression to each item in an iterable.
Nested Lists
Lists can contain other lists (2D or multi-dimensional structures).
Tuples
Tuples are ordered, immutable sequences in Python. Unlike lists, you cannot modify (add/remove/change) the elements of a tuple once it’s created. Tuples are useful for fixed data collections, safer data handling, and as dictionary keys.
Creating Tuples
You can define tuples with parentheses ()
or without (comma is what defines a tuple):
Tuple Unpacking
You can extract values from a tuple directly into variables:
You can also use the *
operator for extended unpacking:
Tuple Methods
Tuples have fewer methods than lists due to immutability:
Named Tuples
For readable and self-documenting tuples, use namedtuple
from the collections
module:
Named tuples behave like regular tuples but allow access to elements by name.
Dictionaries
Dictionaries are unordered, mutable collections in Python used to store data in key-value pairs. They are one of the most powerful and flexible data structures in Python.
Creating Dictionaries
Keys must be immutable (like strings, numbers, or tuples), and values can be any type.
Accessing Values
Dictionary Methods
Dictionary Comprehensions
Quickly create or transform dictionaries:
Nested Dictionaries
Dictionaries can contain other dictionaries, useful for structured data:
Sets
Sets are unordered collections of unique elements. They are useful when you need to store non-duplicate items, perform mathematical set operations, or check for membership efficiently.
Creating Sets
Sets can contain any immutable types (e.g., numbers, strings, tuples).
Set Operations
Python sets support mathematical operations:
Set Methods
Set Comprehensions
Like list/dict comprehensions, but for sets:
Control Flow
Conditional Statements
Control flow in Python allows you to execute code based on certain conditions. Conditional statements help your program make decisions and follow different paths depending on the data.
if
, elif
, else
The most basic conditional structure:
- You can have multiple
elif
blocks but only oneif
and oneelse
. - Blocks are defined by indentation, not curly braces.
Nested Conditions
You can place one condition inside another:
Use nested conditions carefully to avoid deeply indented code (which can be harder to read).
Ternary Operator (Inline if
)
For simple one-line conditions:
It’s equivalent to:
Match-Case (Python 3.10+)
A more readable alternative to long if-elif
chains, similar to switch
in other languages:
_
acts as the default case.- Match-case is pattern matching, not just value comparison.
Loops
Loops in Python are used to execute a block of code multiple times. Python provides two main types of loops: for
and while
. You can control the loop flow using keywords like break
, continue
, and even use an else
block with a loop.
for
Loops
Used to iterate over a sequence (list, string, tuple, etc.):
You can loop over strings:
while
Loops
Repeatedly runs as long as the condition is True
:
range()
Function
Generates a sequence of numbers, commonly used with for
loops:
break
and continue
Control the flow inside loops:
Loop with else
The else
block runs only if the loop completes normally (no break):
If a break
is encountered, the else
part is skipped.
Nested Loops
You can place one loop inside another to work with multi-dimensional data:
Loop Control
Python provides powerful built-in functions like enumerate()
and zip()
to simplify and optimize how you loop through data. You can also iterate directly over dictionary keys and values in an intuitive way.
enumerate()
Use enumerate()
when you need both the index and the value during iteration.
You can also set a custom starting index:
zip()
Use zip()
to iterate over two (or more) sequences in parallel.
If the lists are of unequal length, zip()
stops at the shortest one.
Iterating Over Dictionaries
You can iterate through keys, values, or both using built-in methods:
Functions
Function Basics
Functions in Python are reusable blocks of code that perform a specific task. They help make code more modular, readable, and organized. You can define your own functions using the def
keyword.
Defining Functions
Call the function using its name:
Function Parameters and Arguments
Functions can accept parameters (placeholders) and work with actual arguments (values) when called:
You can pass multiple arguments:
Return Statements
Use return
to send a value back from the function:
If there’s no return
, the function returns None
by default.
Default Parameters
Provide default values for parameters:
Keyword Arguments
You can pass arguments using the key=value
syntax:
Keyword arguments improve clarity and allow flexible ordering.
Advanced Function Concepts
Beyond basic function definitions, Python provides powerful features like flexible argument handling, anonymous functions, scoping rules, and decorators. Mastering these allows you to write cleaner, more reusable, and dynamic code.
*args
and **kwargs
Used to handle variable numbers of arguments in functions.
*args
→ collects positional arguments into a tuple.**kwargs
→ collects keyword arguments into a dictionary.
Output:
Lambda Functions
Anonymous, one-line functions used for short tasks:
Often used with functions like map()
, filter()
, or sorted()
.
Scope: Local vs Global
- Local: variables defined inside a function — accessible only there.
- Global: variables defined outside — accessible anywhere (unless shadowed locally).
global
and nonlocal
Keywords
Use global
to modify a global variable inside a function:
Use nonlocal
to modify a variable from an enclosing (non-global) scope:
Decorators (Basic)
Decorators are functions that wrap other functions to extend or modify their behavior.
Output:
File Handling
Python makes it easy to work with files — whether you’re reading data, writing logs, or handling configurations. The open()
function is your gateway to file manipulation, and the with
statement ensures files are managed safely.
Opening Files with open()
The open()
function returns a file object:
Basic syntax:
Reading Files
.read()
– Read entire file content as a string:
.readline()
– Read one line at a time:
.readlines()
– Read all lines as a list:
Writing Files
.write()
– Write a single string to the file:
.writelines()
– Write a list of strings:
Important: Writing (
'w'
) overwrites the file if it exists.
File Modes
Mode | Description |
---|---|
'r' | Read (default) |
'w' | Write (creates or overwrites) |
'a' | Append (adds to end) |
'x' | Create (fails if exists) |
'b' | Binary mode |
't' | Text mode (default) |
'+' | Read and write mode |
Examples:
Context Managers (with
Statement)
Recommended way to handle files — automatically closes the file:
This ensures file resources are properly released, even if an error occurs.
File Methods
Once you’ve opened a file using Python’s open()
function, you can use various methods to manage reading, writing, and file position. Python also has built-in modules for working with structured file formats like CSV and JSON.
.close()
, .seek()
, .tell()
.close()
Closes the file and frees system resources:
Best practice: Use
with
blocks to handle closing automatically.
.tell()
Returns the current file cursor position (in bytes):
.seek()
Moves the file cursor to a specific position:
Working with CSV Files (csv
module)
The csv
module helps in reading and writing CSV (Comma-Separated Values) files.
For dictionaries:
JSON File Operations (json
module)
The json
module is used for reading and writing JSON data.
Other useful functions:
json.dumps()
→ converts Python object to JSON stringjson.loads()
→ parses JSON string to Python object
Exception Handling
Try-Except
Exception handling in Python allows your program to gracefully handle errors instead of crashing. This is done using try
, except
, else
, and finally
blocks.
Basic try-except
Wrap risky code in a try
block, and handle errors in the except
block:
Output:
Multiple except
Blocks
You can handle different types of exceptions separately:
Specific Exceptions
Always try to catch specific exceptions, not general ones. This makes debugging easier and avoids hiding real bugs.
else
and finally
Blocks
else
: Runs if no exceptions occur.finally
: Always runs, whether or not there was an exception.
Output:
Use finally
for cleanup tasks like closing files or releasing resources.
Common Exceptions
Python has many built-in exceptions, and knowing the most common ones helps you catch and debug errors effectively. Here are some that you’ll frequently encounter:
ValueError
Occurs when a function receives an argument of the correct type but an inappropriate value.
TypeError
Raised when an operation or function is applied to an object of inappropriate type.
IndexError
Occurs when trying to access an index that is out of range in a sequence.
KeyError
Happens when you try to access a dictionary key that doesn’t exist.
Use .get()
to avoid this:
FileNotFoundError
Raised when trying to open a file that doesn’t exist.
ZeroDivisionError
Happens when a number is divided by zero.
Custom Exceptions
You can define your own exceptions by inheriting from the Exception
class:
Output:
Custom exceptions are useful for application-specific error handling.
Object-Oriented Programming
Classes and Objects
Python supports object-oriented programming (OOP), a method of structuring code using classes and objects. It helps model real-world entities and encourages code reuse and organization.
Class Definition
A class is like a blueprint for creating objects.
This defines an empty class named Person
.
Creating Objects
An object is an instance of a class.
Instance Variables and Methods
You can define data (variables) and behaviors (methods) inside the class:
Create and use the object:
__init__
Method
- A special method called automatically when a new object is created.
- It’s used to initialize instance variables.
self
Keyword
- Refers to the current object instance.
- Used to access variables and methods inside the class.
OOP Concepts
Object-Oriented Programming in Python allows for more advanced features like inheritance, method overriding, and shared or independent variables and methods. These features make your code more flexible, extensible, and reusable.
Inheritance
A class can inherit properties and methods from another class (called the parent or base class):
Method Overriding
A child class can override methods from the parent class:
super()
Function
Used to call methods from the parent class, especially useful in method overriding:
Output:
Class Variables vs Instance Variables
- Instance variables: Unique to each object.
- Class variables: Shared across all instances of the class.
Static Methods and Class Methods
Static Method: Doesn’t access instance or class data
Class Method: Receives the class itself (cls
) as the first argument
Use static methods for utility functions, and class methods when modifying or accessing class-level data.
Special Methods
Special methods in Python (also called magic methods or dunder methods) let you define how your custom objects behave with built-in functions and operators. They all start and end with double underscores (e.g., __init__
, __str__
).
__str__
and __repr__
Both define how your object is represented as a string.
__str__
: For readable string output (used byprint()
).__repr__
: For unambiguous representation (used in debugging or in the interpreter).
__len__
, __getitem__
, __setitem__
These let your objects behave like collections (lists, dicts, etc.).
Usage:
Operator Overloading
You can redefine how operators behave for your custom objects by implementing special methods like:
__add__
→+
__sub__
→-
__mul__
→*
__eq__
→==
__lt__
→<
Example:
Modules and Packages
Importing
Python supports modular programming through modules and packages. A module is simply a .py
file containing Python code (functions, classes, variables). A package is a folder containing multiple modules and an __init__.py
file.
To use code from other modules, you use the import
statement.
import
Statement
Import an entire module:
from ... import
Import specific components directly:
import ... as
Alias a module or function to a shorter name:
Or alias a function:
Importing Specific Functions
You can import just the parts you need from large modules to reduce memory usage and improve readability:
Tip: Use only what you need to keep your code clean and efficient.
Standard Library Modules
Python comes with a rich standard library—a collection of built-in modules that let you perform common tasks without installing third-party packages. Below are some essential and frequently used modules:
math
, random
, datetime
math
– Mathematical functions:
random
– Random number generation:
datetime
– Date and time handling:
os
, sys
, pathlib
os
– Interacting with the operating system:
sys
– Access to system-specific parameters:
pathlib
– Object-oriented file paths:
collections
, itertools
collections
– Specialized container datatypes:
itertools
– Tools for efficient looping:
json
, csv
, re
json
– Working with JSON data:
csv
– Read/write CSV files:
re
– Regular expressions:
These built-in modules save time and are highly optimized for common tasks.
Creating Modules
In Python, you can organize your code into modules and packages to make it more reusable, readable, and maintainable. Creating your own module is simple — it’s just a .py
file that can be imported into other Python scripts.
Creating .py
Files (Custom Modules)
Any .py
file can be used as a module.
Example: math_utils.py
You can now import this module in another script:
if __name__ == "__main__"
This special block lets you run a file both:
- As a script (direct execution)
- As a module (when imported)
So when you import this module somewhere else, greet()
won’t automatically run — it runs only when executed directly.
Package Structure
A package is a folder that contains Python modules and an optional __init__.py
file (required in older Python versions to mark the folder as a package).
Example structure:
my_package
You can then import like this:
You can even make reusable packages and distribute them via tools like pip
.
Built-in Functions
Common Built-ins
Python provides a set of built-in functions that are always available—no import required. These functions make common tasks like getting input, working with collections, or performing math operations much easier.
print()
and input()
len()
and type()
min()
, max()
, sum()
, sorted()
abs()
, round()
, pow()
all()
and any()
enumerate()
and zip()
enumerate()
– Loop with index:
zip()
– Combine two lists element-wise:
These built-ins are powerful and widely used in daily Python coding.
Type Conversion Functions
Python provides built-in functions to convert between data types. These are useful when you’re working with user input, performing calculations, or formatting data for output.
int()
, float()
, str()
, bool()
int()
– Converts to integer:
float()
– Converts to float:
str()
– Converts to string:
bool()
– Converts to boolean:
Tip: Empty values (like
0
,''
,[]
,None
) becomeFalse
. Everything else isTrue
.
list()
, tuple()
, dict()
, set()
list()
– Converts to list:
tuple()
– Converts to tuple:
dict()
– Converts to dictionary (from key-value pairs):
set()
– Converts to set (removes duplicates):
These functions are essential when transforming data between types in real-world applications.
Utility Functions
Python offers several built-in utility functions that help with data processing, introspection, and debugging. These functions make your code cleaner and more efficient.
map()
, filter()
, reduce()
map(function, iterable)
Applies a function to every item in an iterable and returns a map object.
filter(function, iterable)
Returns items from an iterable for which the function returns True
.
- reduce(function, iterable)
Applies a rolling computation to sequential pairs in an iterable. (Requires functools
module)
isinstance()
, hasattr()
, getattr()
isinstance(object, classinfo)
Checks if an object is an instance of a class or tuple of classes.
hasattr(object, name)
Checks if an object has an attribute with the given name.
getattr(object, name, default)
Gets the attribute value of an object; returns default
if attribute doesn’t exist.
dir()
, help()
, id()
dir(object)
Lists attributes and methods of an object.
- help(object)
Shows the documentation/help for an object or module.
- id(object)
Returns the unique identifier (memory address) of an object.
These utility functions are essential tools for working with data and understanding Python objects.
List/Dict/Set Comprehensions
List Comprehensions
List comprehensions provide a concise way to create lists by applying an expression to each item in an iterable. They are more readable and often faster than traditional loops.
Basic Syntax
Example: Create a list of squares
With Conditions
You can add an if
condition to filter items:
Nested Comprehensions
For nested loops, list comprehensions can be combined:
Multiple Iterables
You can iterate over multiple iterables simultaneously using nested loops:
List comprehensions make your code concise and pythonic. They are widely used for transforming and filtering data efficiently.
Dictionary Comprehensions
Dictionary comprehensions provide a compact way to create dictionaries by generating key-value pairs from an iterable or another dictionary. They are similar to list comprehensions but build dictionaries instead of lists.
Basic Syntax
Example: Create a dictionary mapping numbers to their squares:
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
With Conditions
You can add an if
condition to include only certain items:
# Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Key-Value Transformations
You can transform both keys and values during comprehension:
Example: Convert a list of strings to a dictionary mapping each string to its length:
lengths = {word: len(word) for word in words}
# Output: {‘apple’: 5, ‘banana’: 6, ‘cherry’: 6}
Dictionary comprehensions are a powerful and readable way to build dictionaries dynamically.
Set Comprehensions
Set comprehensions let you create sets in a concise and readable way, similar to list and dictionary comprehensions. They automatically handle duplicates since sets only store unique values.
Basic Syntax
Example: Create a set of squares:
# Output: {0, 1, 4, 9, 16}
With Conditions
You can add conditions to filter items:
# Output: {0, 4, 16, 36, 64}
Set comprehensions are useful when you want to quickly create a set based on some logic or filtering.
Regular Expressions
re
Module
Python’s re
module provides powerful tools for pattern matching and text processing using regular expressions.
re.search()
, re.match()
, re.findall()
# re.search() – Searches for a match anywhere in the string
match = re.search(r”\d+”, “Order #12345”)
print(match.group()) # 12345
# re.match() – Matches only at the beginning of the string
result = re.match(r”Hello”, “Hello world”)
print(result.group()) # Hello
# re.findall() – Finds all matching patterns
numbers = re.findall(r”\d+”, “A1 B22 C333”)
print(numbers) # [‘1′, ’22’, ‘333’]
re.sub()
, re.split()
clean = re.sub(r”\s+”, “-“, “Hello World”)
print(clean) # Hello-World
# re.split() – Split string based on pattern
parts = re.split(r”\s+”, “Split this sentence”)
print(parts) # [‘Split’, ‘this’, ‘sentence’]
Pattern Compilation
Compiled patterns improve performance when the same regex is used repeatedly.
print(pattern.findall(“ID 101, 202, 303”)) # [‘101’, ‘202’, ‘303’]
Common Patterns (Regular Expressions)
When writing regular expressions in Python, you use special symbols to define the kind of pattern you’re looking for. Below are some of the most frequently used pattern types:
Character Classes
Character classes match any one character from a set.
re.findall(r”[aeiou]”, “hello world”) # [‘e’, ‘o’, ‘o’]
re.findall(r”[A-Z]”, “My Name Is GPT”) # [‘M’, ‘N’, ‘I’, ‘G’]
re.findall(r”\\d”, “Age 25”) # [‘2’, ‘5’]
re.findall(r”\\w”, “Hi!”) # [‘H’, ‘i’]
re.findall(r”\\s”, “a b\\tc\\nd”) # [‘ ‘, ‘\\t’, ‘\\n’]
[abc]
→ matches ‘a’, ‘b’, or ‘c’\d
→ digits (0–9)\w
→ word characters (letters, digits, underscore)\s
→ whitespace (space, tab, newline)
2. Quantifiers
Quantifiers specify how many times a pattern must occur.
re.findall(r”b{2}”, “abbba”) # [‘bb’]
re.findall(r”\\d{1,3}”, “1234567”) # [‘123’, ‘456’, ‘7’]
*
→ 0 or more+
→ 1 or more?
→ 0 or 1{n}
→ exactly n times{n, m}
→ between n and m times
3. Anchors
Anchors match positions in the string (not characters).
re.findall(r”end$”, “The story ends”) # []
re.findall(r”end$”, “This is the end”) # [‘end’]
^
→ beginning of string
$
→ end of string
\b
→ word boundary
\B
→ not a word boundary
4. Groups and Capturing
Use parentheses ()
to group parts of a regex and extract matched subpatterns.
print(match.group(1)) # Alice
match = re.search(r”(\\d{2})/(\\d{2})/(\\d{4})”, “Date: 12/07/2025”)
print(match.groups()) # (’12’, ’07’, ‘2025’)
()
→ capture groups
group(n)
→ returns nth group
groups()
→ returns all matched groups as a tuple
Working with APIs and JSON
JSON Operations
Python’s json
module makes it easy to work with JSON data — whether you’re loading data from a file or converting Python objects into JSON format to send via an API.
Import JSON module first:
json.loads()
and json.dumps()
These are used to convert between JSON strings and Python objects.
json.load()
and json.dump()
These are used to read from or write to JSON files.
Working with JSON Data
You typically use these methods when dealing with:
- API responses (often as JSON strings)
- Config files
- Data interchange between systems
JSON maps directly to Python types:
- JSON Object → Python
dict
- JSON Array → Python
list
- JSON String → Python
str
- JSON Number → Python
int
/float
true
/false
→True
/False
null
→None
HTTP Requests (requests module)
Python’s requests
module is a powerful and easy-to-use HTTP client library for making API calls, such as GET
and POST
requests, handling headers, and reading responses.
First, install the module (if not already):
Then import it in Python:
Sending a GET Request
You can pass query parameters using the params
argument:
Sending a POST Request
For sending JSON data:
Setting Headers
Response Handling
Common response attributes:
response.text
– Raw response textresponse.json()
– Parse JSON to dictresponse.status_code
– HTTP status coderesponse.headers
– Response headers
Date and Time
datetime
Module
Python’s built-in datetime
module allows you to work with dates and times — from creating and formatting to parsing and calculating time differences.
Importing the module:
datetime.now()
and datetime.today()
Both give the current local date and time.
Creating datetime
Objects
You can create custom date-time objects manually:
Formatting Dates with strftime()
Use .strftime()
to convert a datetime
object to a string in your desired format.
Common format codes:
%Y
→ Year (2025)%m
→ Month (01–12)%d
→ Day (01–31)%H:%M:%S
→ Hour, Minute, Second
Parsing Strings with strptime()
Use .strptime()
to convert a string into a datetime
object.
Time Operations
Python’s datetime
module, along with timedelta
and timezone
, lets you perform arithmetic with dates and times, measure durations, and manage timezones.
Time Arithmetic with timedelta
timedelta
represents the difference between two dates or times.
You can also add or subtract minutes, hours, or weeks:
timedelta
Objects
You can calculate durations:
Timezone Handling
Use timezone
from the datetime
module to manage time zones.
To convert between timezones, you can use .astimezone()
:
Debugging and Testing
Debugging
Debugging helps identify and fix bugs in your Python code. Python offers several tools and techniques to make debugging more efficient.
1. print()
Debugging (Basic)
Using print()
is the simplest way to trace variable values or code execution:
While not ideal for large projects, it works well for quick checks.
2. Using the pdb
Debugger (Built-in)
Python’s built-in interactive debugger lets you pause and inspect code line by line.
While debugging, you can use commands like:
n
→ next linec
→ continue executionp variable
→ print variableq
→ quit debugger
3. Common Debugging Techniques
- Check edge cases (e.g., 0, empty strings/lists, None)
- Use try-except blocks to catch and understand exceptions
- Isolate the bug by testing functions individually
- Add assertions to validate assumptions:
Error Handling Best Practices
Handling errors properly improves code reliability and maintainability. Here are some best practices to follow in Python:
Logging
Use Python’s built-in logging
module instead of print()
for recording events, errors, and debugging info. It provides more control over message levels and outputs.
Logging levels include: DEBUG, INFO, WARNING, ERROR, CRITICAL.
Assert Statements
Use assert
to test assumptions during development. If the condition is false, Python raises an AssertionError
.
Assertions help catch bugs early by validating inputs or states.
Unit Testing Basics
Unit tests check small parts of your code automatically to ensure they work correctly.
Python’s built-in unittest
module helps create tests:
Run tests frequently to catch errors before deployment.
Performance and Best Practices
Code Optimization
Writing efficient Python code improves speed and reduces resource use. Here are key concepts and tools:
Time Complexity Basics
- Measures how execution time grows with input size.
- Common complexities:
- O(1) — constant time
- O(n) — linear time
- O(n²) — quadratic time
- Aim to use algorithms with lower time complexity for better performance.
Memory Usage
- Efficient use of memory prevents slowdowns and crashes.
- Avoid unnecessary copies of large data structures.
- Use generators and iterators to handle large data lazily.
Profiling Code
Profiling helps identify bottlenecks in your code.
- Use built-in
cProfile
module:
- For line-by-line profiling, use
line_profiler
(requires installation).
Optimizing code is about balancing speed, memory, and readability.
Python Best Practices
Following best practices helps keep your Python code clean, maintainable, and professional.
PEP 8 Style Guide
- PEP 8 is the official Python style guide.
- It covers naming conventions, indentation (4 spaces), line length (max 79 characters), spacing, imports, and more.
- Use tools like flake8 or black to check and auto-format code.
Code Organization
- Break code into functions and classes.
- Group related functions in modules (.py files).
- Use packages (folders with
__init__.py
) to organize modules. - Keep scripts and libraries separate.
Documentation Strings (Docstrings)
- Use triple quotes
""" """
to document modules, classes, and functions. - Explain purpose, parameters, and return values.
- Good docstrings improve code readability and help generate docs automatically.
Virtual Environments
- Use virtual environments to isolate project dependencies.
- Avoids conflicts between packages used by different projects.
Create and activate virtual environment:
Install packages within this environment without affecting system Python.
Common Patterns and Idioms
Pythonic Code
Pythonic code means writing in a way that is clear, concise, and uses Python’s best features and idioms.
List Comprehensions vs Loops
List comprehensions provide a compact way to create lists:
Context Managers
Use with
statements to manage resources like files, ensuring proper cleanup:
Generator Expressions
Generators produce items one at a time, saving memory:
Unpacking Sequences
Unpack tuples, lists, or other iterables easily:
Common Algorithms
Understanding basic algorithms helps you solve problems efficiently in Python.
Sorting Algorithms
Python’s built-in sorted()
and list .sort()
use Timsort, a hybrid sorting algorithm with O(n log n) average time complexity.
For custom sorting:
Searching Algorithms
- Linear Search: Check each element until found (O(n)).
- Binary Search: Efficient for sorted lists (O(log n)).
Basic Data Structure Operations
- Stacks: Use list with
.append()
and.pop()
(LIFO).
- Queues: Use
collections.deque
for efficient FIFO.
- Linked Lists, Trees, Graphs: Typically implemented with custom classes.
Command Line and System
sys
Module
The sys
module provides access to system-specific parameters and functions that interact closely with the Python interpreter.
Import it like this:
sys.argv
– Command Line Arguments
Used to access arguments passed to a Python script from the terminal.
Run from terminal:
Output:
sys.path
– Module Search Paths
Shows the list of directories where Python looks for modules.
You can modify this list to add custom module locations.
sys.version
– Python Version Info
sys.exit()
– Exiting a Script
Gracefully exit the program manually.
os
Module
The os
module in Python lets you interact with the operating system — including working with files, directories, and environment variables.
Import it first:
os.getcwd()
& os.chdir()
os.getcwd()
→ Returns the current working directoryos.chdir(path)
→ Changes the working directory
os.listdir()
Returns a list of files and directories in the given path.
os.path
Operations
These functions help with safe path handling:
Environment Variables
You can access and modify system environment variables.
Advanced Topics (Brief)
Generators and Iterators
Generators and iterators are used for efficient data processing, especially with large datasets, as they produce values on demand.
yield
Keyword
Generators are functions that use yield
instead of return
. They pause execution and resume where they left off, saving memory.
Output:
Generator Expressions
Like list comprehensions but with ()
instead of []
. They return a generator object (lazy evaluation).
for
LoopIterator Protocol
An iterator is any object that implements:
__iter__()
→ returns the iterator object itself__next__()
→ returns the next item or raisesStopIteration
Example:
iter()
and next()
Custom iterator:
__iter__
& __next__
Context Managers
Context managers handle setup and cleanup actions automatically. The most common example is using the with
statement when working with files, which ensures proper resource management.
with
Statement
Used to wrap the execution of a block with methods for setup and teardown.
with open()
Even if an error occurs inside the block, the file is safely closed.
Creating Custom Context Managers
You can create your own context manager in two ways:
1. Using a Class (__enter__
and __exit__
methods)
__enter__
/ __exit__
Output:
2. Using the contextlib
Module
For simpler context managers, use a generator with contextlib.contextmanager
:
@contextmanager
Decorators
Decorators allow you to modify or enhance functions and classes without changing their actual code. They are widely used in Python for logging, access control, caching, and more.
Function Decorators
A function decorator wraps another function, often using closures.
Output:
@greet
is equivalent to: say_name = greet(say_name)
Class Decorators
Decorators can also be used with classes to modify or wrap class behavior.
__repr__
Common Decorator Patterns
- Logging
Automatically logs function calls: pythonCopyEdit
logger
2. Timing
Measure how long a function takes:
timer
- Access Control / Authorization
Useful in web apps to check permissions. - Memoization / Caching
Store results to speed up repeated calls (like@lru_cache
fromfunctools
).
Conclusion
You now have the complete roadmap to Python mastery. This cheat sheet covers everything from basic syntax to advanced concepts that professional developers use daily.
Leave a Comment