0% found this document useful (0 votes)
4 views1 page

Python Cheatsheet

This Python cheatsheet serves as a quick reference for essential syntax, structures, and advanced features in Python, catering to both beginners and experienced developers. It covers core concepts such as data types, functions, control flow, object-oriented programming, and file management, along with advanced topics like decorators and virtual environments. The document also includes practical examples and explanations for various Python functionalities, making it a comprehensive guide for modern Python development.

Uploaded by

kejati5914
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

Python Cheatsheet

This Python cheatsheet serves as a quick reference for essential syntax, structures, and advanced features in Python, catering to both beginners and experienced developers. It covers core concepts such as data types, functions, control flow, object-oriented programming, and file management, along with advanced topics like decorators and virtual environments. The document also includes practical examples and explanations for various Python functionalities, making it a comprehensive guide for modern Python development.

Uploaded by

kejati5914
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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 Functions & Control Data Structures


Operators, data types, variables Definitions, parameters, flow control Lists, dicts, sets, tuples

Advanced Patterns File & Package Management


OOP, decorators, comprehensions I/O operations, virtual environments

Basics: Operators & Data Types

Operator Precedence Core Data Types

Operators determine how values are combined. Precedence Python's fundamental data types define the kind of values
dictates the order of operations. variables can hold.

** > % // / * > - + # int (integer, whole number)


age = 25
# 20 (multiplication before addition) # float (floating-point number, decimal)
2+3*6 price = 19.99
# 30 (parentheses override precedence) # str (string, sequence of characters)
(2 + 3) * 6 name = "Alice"
# 256 (exponentiation) # bool (boolean, True or False)
2 ** 8 is_student = True
# list (ordered, mutable collection)
scores = [85, 92, 78]
# dict (dictionary, key-value pairs)
person = {'name': 'Bob'}

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

Lists (Mutable) Tuples (Immutable)


Lists are ordered collections of items that can be changed after Tuples are ordered collections similar to lists, but they cannot be
creation. changed after creation.

furniture = ['table', 'chair'] coords = (10, 20)


# 'table' (access item by index) # 10 (access item by index)
furniture[0] coords[0]
# slice (get a sub-list)
furniture[1:3] # Cannot modify once created
# Add item to end # coords[0] = 15 # Error! (attempting to change an
[Link]('bed') immutable tuple)
# Remove specific item
[Link]('chair')
# Sort items in place
[Link]()

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.

Create Sets Set Operations

Sets can be created from a list or by directly listing elements. Perform mathematical set operations like union, intersection,
and difference.
# Directly create a set
s = {1, 2, 3} s1 = {1, 2, 3}
# Convert a list to a set s2 = {3, 4, 5}
s = set([1, 2, 3])
# {1,2,3,4,5} (all unique elements from both sets)
[Link](s2)
# {3} (elements common to both sets)
[Link](s2)
# {1,2} (elements in s1 but not in s2)
[Link](s2)

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

1 2 3

Conditionals For Loops While Loops


Use `if`, `elif` (else if), and `else` for Iterate over a sequence (like a list, tuple, Repeats a block of code as long as a
decision-making logic. or string) or other iterable objects. specified condition is true.

if name == 'Debora': pets = ['Bella', 'Milo'] count = 0


# Executes if name is 'Debora' # Loop through each item in the # Loop continues while count is
print('Hi!') 'pets' list less than 5
elif name == 'George': for pet in pets: while count < 5:
# Executes if name is 'George' print(pet) print('Hello')
print('Hello!') # Increment count to eventually
else: stop the loop
# Executes if neither of the count += 1
above conditions are met
print('Who?')

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 [Link]('C')]

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


# {"ABC", "DEF"} (converts strings to uppercase)
{[Link]() 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 [Link]()}

String Formatting: Modern Approach

F-Strings (Python 3.6+) Format Numbers

F-strings (formatted string literals) provide a readable and F-strings also allow for flexible number formatting.
efficient way to embed expressions inside string literals.

amount = 10000000
name = 'Elizabeth' # '10,000,000' (add comma thousands separator)
# Embeds variable directly f"{amount:,}"
f'Hello {name}!'
pi = 3.1415926
a=5 # '3.14' (format to two decimal places)
b = 10 f"{pi:.2f}"
# Embeds an expression
f'Sum is {a + b}'

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)
[Link]()
# 'hello world!' (converts to lowercase)
[Link]()
# 'Hello World!' (capitalizes the first letter of each word)
[Link]()

# 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 = [Link](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)
[Link]()

# Groups: Use parentheses in the regex to capture specific parts of the match.
phone_regex = [Link](r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
# '415' (first group)
[Link](1)
# '555-4242' (second group)
[Link](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-Except Custom Exceptions

Use `try`, `except`, and `finally` blocks to catch and manage Define your own exception classes for specific error conditions
exceptions. in your application.

try: # Inherit from base Exception class


# This will raise a ZeroDivisionError class MyException(Exception):
result = 10 / 0 pass
# Catch specific error type
except ZeroDivisionError: # Raise an instance of your custom exception
print('Cannot divide by 0') raise MyException('Custom error')
# Always executes, regardless of exception
finally:
print('Cleanup')

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('[Link]') as f:
content = [Link]()

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


with open('[Link]') 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('[Link]', 'w') as f:
[Link]('Hello world!\n')

# Append: Open a file for appending. New content is added to the end of the file.
with open('[Link]', 'a') as f:
[Link]('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.


[Link]()

# Create directories: Make new directories, optionally creating parent directories if they don't exist.
([Link]() / '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('[Link]').exists()
# True if it's a file
Path('[Link]').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.
@[Link](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:

01 02 03

Encapsulation Inheritance Polymorphism


Bundling data (attributes) and methods Allows a class (child/subclass) to inherit Means "many forms." It allows objects of
that operate on the data within a single attributes and methods from another class different classes to be treated as objects of
unit (class). It restricts direct access to (parent/superclass), promoting code a common base class, responding to the
some of an object's components. reusability. same method call in different ways.

class MyClass: class Animal: # Parent class class Shape: # Base class
def __init__(self): # Placeholder method def area(self): pass
# Convention for protected def speak(self): pass
member class Rectangle(Shape): # Subclass
self._protected = 10 class Dog(Animal): # Child class # Specific implementation of area
# Name mangling for private inheriting from Animal for Rectangle
member # Overrides parent's speak def area(self):
self.__private = 20 method return w * h
def speak(self):
print("Woof!")

Dataclasses: Simplified Classes


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

Basic Dataclass With Defaults

Define data-holding classes with minimal boilerplate. Assign default values to fields directly in the class definition.

from dataclasses import dataclass @dataclass


class Product:
# Decorator to create a dataclass name: str
@dataclass # Field with default value
class Number: count: int = 0
# Type-hinted field # Another field with default
val: int price: float = 0.0

obj = Number(2) # 'count' and 'price' use their defaults


[Link] # 2 obj = Product("Python")
[Link] # 0

JSON & YAML


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

JSON YAML

JavaScript Object Notation (`json` module) is widely used for YAML Ain't Markup Language (`[Link]` is a common
web data. library) is often used for configuration files due to its human-
friendly syntax.

import json
from [Link] import YAML
# Read: Load JSON data from a file into a Python object
(dictionary/list). # Initialize YAML parser
with open("[Link]", "r") as f: yaml = YAML()
content = [Link](f) with open("[Link]") as f:
# Load YAML data from a file
# Write: Dump Python data (dictionary/list) to a JSON data = [Link](f)
formatted file.
data = {"name": "Joe", "age": 20}
with open("[Link]", "w") as f:
# 'indent' makes the output human-readable
[Link](data, f, indent=2)

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

virtualenv Poetry UV (Fast)


A tool to create isolated Python A dependency management and A modern, fast Python package
environments. packaging tool for Python. installer and resolver.

# Install virtualenv # Install Poetry # Install UV


pip install virtualenv pip install poetry curl -LsSf
# Create a new environment # Create a new project with a [Link] |
mkvirtualenv HelloWorld virtual environment sh
# Activate the environment poetry new my-project # Initialize a project with UV
workon HelloWorld # Add a dependency uv init my-project
# Deactivate the environment poetry add pendulum # Add a package
deactivate # Install dependencies uv add requests
poetry install # Run a script within the UV
environment
uv run python [Link]

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. map() - Applies a given function to each item of an iterable

all() - Returns True if all elements in an iterable are true. and returns a map object.
max() / min() - Returns the largest/smallest item in an
any() - Returns True if any element in an iterable is true.
iterable or between two or more arguments.
enumerate() - Adds a counter to an iterable, returning it as
range() - Generates an immutable sequence of numbers.
an enumerate object.
sorted() - Returns a new sorted list from the items in an
filter() - Constructs an iterator from elements of an iterable
iterable.
for which a function returns true.
sum() - Sums the items of an iterable.
len() - Returns the number of items in an object.
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.

Exceptions & Assertions Logging

Exceptions signal errors, while assertions check for conditions Logging provides a way to track events that happen when some
that must be true at a certain point in code. software runs, offering more flexibility than print statements for
debugging and monitoring.

# Raise exception: Explicitly trigger an error.


raise Exception('Error message') import logging

# Assertion: Verify a condition. If false, it raises an # Configure basic logging to show debug messages
AssertionError. [Link](
status = 'open' # Set the logging level (DEBUG, INFO, WARNING,
# The message is shown if assertion fails ERROR, CRITICAL)
assert status == 'open', 'Must be open' level=[Link],
# Define output format
format='%(asctime)s - %(levelname)s - %(message)s'
)
# Log a debug message
[Link]('Program started')

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

[Link]

You might also like