
Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

labex.io
This cheatsheet provides a quick reference to fundamental Python concepts, syntax, and advanced features, ideal for both beginners and experienced developers.
Operators, data types, variables
Definitions, parameters, flow control
Lists, dicts, sets, tuples
OOP, decorators, comprehensions
I/O operations, virtual environments
2 + 3 * 6
(2 + 3) * 6
2 ** 8
Operators determine how values are combined. Precedence dictates the order of operations.
age = 25
price = 19.
name = "Alice"
is_student = True
scores = [85, 92, 78]
person = {'name': 'Bob'}
Python's fundamental data types define the kind of values variables can hold.
Functions allow you to encapsulate reusable blocks of code.
def say_hello(name): print(f'Hello {name}')
say_hello('Carlos')
def sum_two_numbers(a, b):
return a + b
add = lambda x, y: x + y add(5, 3) # 8
furniture = ['table', 'chair']
furniture[0]
furniture[1:3]
furniture.append('bed')
furniture.remove('chair')
furniture.sort()
Lists are ordered collections of items that can be changed after creation.
coords = (10, 20)
coords[0]
immutable tuple)
Tuples are ordered collections similar to lists, but they cannot be changed after creation.
Dictionaries store data in unordered key-value pairs, allowing efficient lookup by key.
my_cat = { 'size': 'fat', 'color': 'gray', 'disposition': 'loud' }
my_cat['age_years'] = 2
for key, value in my_cat.items(): print(f'{key}: {value}')
my_cat.get('breed', 'unknown')
Sets are unordered collections of unique items, useful for membership testing and eliminating duplicates.
s = {1, 2, 3}
s = set([1, 2, 3])
Sets can be created from a list or by directly listing elements.
s1 = {1, 2, 3} s2 = {3, 4, 5}
s1.union(s2)
s1.intersection(s2)
s1.difference(s2)
Perform mathematical set operations like union, intersection, and difference.
Control flow statements determine the order in which code instructions are executed.
if name == 'Debora':
print('Hi!') elif name == 'George':
print('Hello!') else:
above conditions are met print('Who?')
Use if, elif (else if), and else for decision-making logic.
pets = ['Bella', 'Milo']
'pets' list for pet in pets: print(pet)
Iterate over a sequence (like a list, tuple, or string) or other iterable objects.
count = 0
less than 5 while count < 5: print('Hello')
stop the loop count += 1
Repeats a block of code as long as a specified condition is true.
Comprehensions offer a concise way to create lists, sets, or dictionaries based on existing iterables.
names = ['Charles', 'Susan', 'Patrick']
new_list = [n for n in names if n.startswith('C')]
{s.upper() for s in {"abc", "def"}}
c = {'name': 'Pooka', 'age': 5}
{v: k for k, v in c.items()}
name = 'Elizabeth'
f'Hello {name}!'
a = 5 b = 10
f'Sum is {a + b}'
F-strings (formatted string literals) provide a readable and efficient way to embed expressions inside string literals.
amount = 10000000
f"{amount:,}"
pi = 3.
f"{pi:.2f}"
F-strings also allow for flexible number formatting.
Python offers various methods to work with and modify strings.
spam = 'Hello world!'
spam[0:5]
spam[::-1]
greet = 'Hello world!'
greet.upper()
greet.lower()
greet.title()
', '.join(['cats', 'rats'])
'My name is Simon'.split()
Regular expressions (regex) are powerful tools for pattern matching and text parsing.
import re
phone_regex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = phone_regex.search('My number is 415-555-4242.')
mo.group()
phone_regex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo.group(1)
mo.group(2)
phone_regex.findall('Cell: 415-555-9999 Work: 212-555-0000')
Handle runtime errors gracefully to prevent program crashes and provide meaningful feedback.
try:
result = 10 / 0
except ZeroDivisionError: print('Cannot divide by 0')
finally: print('Cleanup')
Use try, except, and finally blocks to catch and manage exceptions.
class MyException(Exception): pass
raise MyException('Custom error')
Define your own exception classes for specific error conditions in your application.
Interact with the file system to read from or write to files.
with open('file.txt') as f: content = f.read()
with open('file.txt') as f:
for line in f: print(line, end='')
with open('output.txt', 'w') as f: f.write('Hello world!\n')
with open('output.txt', 'a') as f: f.write('Additional line')
The pathlib module offers an object-oriented approach to filesystem paths, making operations cleaner and more robust.
from pathlib import Path
print(Path('usr') / 'bin' / 'spam')
Path.cwd()
(Path.cwd() / 'new' / 'folder').mkdir(parents=True)
Path('file.py').exists()
Path('file.py').is_file()
Path('/').is_dir()
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):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("Before function")
result = func(*args, **kwargs)
print("After function") return result return wrapper
@your_decorator def foo(): print("Hello World!")
foo() # Calling foo() now runs the wrapper logic around it
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')
Object-Oriented Programming (OOP) structures code using objects that contain data and methods. Key concepts include:
class MyClass: def init(self):
member self._protected = 10
member self.__private = 20
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
def speak(self): pass
class Dog(Animal): # Child class inheriting from Animal
method def speak(self): print("Woof!")
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
for Rectangle def area(self): return w * h
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 provide a decorator to automatically generate common methods (__init__, __repr__, __eq__) for classes primarily used to store data.
from dataclasses import dataclass
@dataclass class Number:
val: int
obj = Number(2) obj.val # 2
Define data-holding classes with minimal boilerplate.
@dataclass class Product: name: str
count: int = 0
price: float = 0.
obj = Product("Python") obj.count # 0
Assign default values to fields directly in the class definition.
These are common data serialization formats for configuration files and data exchange.
import json
(dictionary/list). with open("data.json", "r") as f: content = json.load(f)
formatted file. data = {"name": "Joe", "age": 20} with open("out.json", "w") as f:
json.dump(data, f, indent=2)
JavaScript Object Notation (json module) is widely used for web data.
from ruamel.yaml import YAML
yaml = YAML() with open("config.yaml") as f:
data = yaml.load(f)
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 isolate Python project dependencies, preventing conflicts between different projects.
pip install virtualenv
mkvirtualenv HelloWorld
workon HelloWorld
deactivate
A tool to create isolated Python environments.
pip install poetry
virtual environment poetry new my-project
poetry add pendulum
poetry install
A dependency management and packaging tool for Python.
curl -LsSf https://astral.sh/uv/install.sh | sh
uv init my-project
uv add requests
environment uv run python script.py
A modern, fast Python package installer and resolver.
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":
result = add(3, 5) print(result)
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.
len([1, 2, 3])
max([1, 5, 3])
sorted([3, 1, 2])
list(zip([1, 2], ['a', 'b']))
Tools and techniques to identify and resolve issues in your code.
raise Exception('Error message')
AssertionError. status = 'open'
assert status == 'open', 'Must be open'
Exceptions signal errors, while assertions check for conditions that must be true at a certain point in code.
import logging
logging.basicConfig(
ERROR, CRITICAL) level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s' )
logging.debug('Program started')
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