Outsourced IT Partner
Support ยท systems ยท strategy
ยฉ 2026
One person, one business โ IT support here, websites at webology.online.
One person, one business โ IT support here, websites at webology.online.
๐ Python Programming Language
Quick Reference & Cheat Sheet - Built-in Functions, Syntax & Standard Library
Basic Syntax
Variables & Assignment
# Variable assignment
name = "Python"
age = 30
is_active = True
# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0
# Augmented assignment
x += 1 # x = x + 1
y *= 2 # y = y * 2
Data Types
# Numbers
integer = 42
floating = 3.14
complex_num = 3 + 4j
# Strings
single_quote = 'Hello'
double_quote = "World"
multiline = """This is a
multiline string"""
# Boolean
is_true = True
is_false = False
# None
nothing = None
Collections
# List (mutable)
my_list = [1, 2, 3, "four"]
# Tuple (immutable)
my_tuple = (1, 2, 3, "four")
# Dictionary
my_dict = {"key": "value", "age": 30}
# Set
my_set = {1, 2, 3, 4}
Built-in Functions
Type & Conversion Functions
type(obj)
isinstance(obj, class)
int(x)
float(x)
str(x)
bool(x)
list(iterable)
tuple(iterable)
dict(mapping)
set(iterable)
Math Functions
abs(x)
round(x, ndigits)
pow(x, y)
min(iterable)
max(iterable)
sum(iterable)
divmod(a, b)
Sequence Functions
len(s)
range(start, stop, step)
enumerate(iterable)
zip(*iterables)
reversed(seq)
sorted(iterable)
all(iterable)
any(iterable)
I/O Functions
print(*objects)
input(prompt)
open(file, mode)
Control Structures
Conditionals
# If statement
if condition:
# code
elif another_condition:
# code
else:
# code
# Ternary operator
result = value_if_true if condition else value_if_false
# Match statement (Python 3.10+)
match value:
case 1:
print("One")
case 2 | 3:
print("Two or Three")
case _:
print("Other")
Loops
# For loop
for item in iterable:
print(item)
# For loop with index
for i, item in enumerate(iterable):
print(i, item)
# While loop
while condition:
# code
if break_condition:
break
if continue_condition:
continue
# For-else and while-else
for item in iterable:
if condition:
break
else:
# executed if loop completed normally
Functions
Function Definition
# Basic function
def greet(name):
return f"Hello, {name}!"
# Function with default parameters
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
# Function with *args and **kwargs
def flexible_func(*args, **kwargs):
print(args) # tuple of positional args
print(kwargs) # dict of keyword args
# Lambda function
square = lambda x: x ** 2
add = lambda x, y: x + y
Decorators
# Simple decorator
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@my_decorator
def say_hello():
print("Hello!")
# Property decorator
class MyClass:
@property
def value(self):
return self._value
@value.setter
def value(self, val):
self._value = val
String Methods
String Operations
str.upper()
str.lower()
str.capitalize()
str.title()
str.strip()
str.lstrip()
str.rstrip()
str.replace(old, new)
str.split(sep)
str.join(iterable)
str.find(sub)
str.index(sub)
str.count(sub)
str.startswith(prefix)
str.endswith(suffix)
str.isdigit()
str.isalpha()
str.isalnum()
str.islower()
str.isupper()
String Formatting
# f-strings (Python 3.6+)
name = "Alice"
age = 30
message = f"Hello, {name}! You are {age} years old."
# .format() method
message = "Hello, {}! You are {} years old.".format(name, age)
message = "Hello, {name}! You are {age} years old.".format(name=name, age=age)
# % formatting (old style)
message = "Hello, %s! You are %d years old." % (name, age)
List Methods
List Operations
list.append(item)
list.insert(index, item)
list.extend(iterable)
list.remove(item)
list.pop(index)
list.clear()
list.index(item)
list.count(item)
list.sort()
list.reverse()
list.copy()
List Comprehensions
# Basic list comprehension
squares = [x**2 for x in range(10)]
# With condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# Nested comprehension
matrix = [[i*j for j in range(3)] for i in range(3)]
# Dictionary comprehension
square_dict = {x: x**2 for x in range(5)}
# Set comprehension
unique_squares = {x**2 for x in range(-5, 6)}
Dictionary Methods
Dictionary Operations
dict.keys()
dict.values()
dict.items()
dict.get(key, default)
dict.setdefault(key, default)
dict.pop(key, default)
dict.popitem()
dict.update(other)
dict.clear()
dict.copy()
dict.fromkeys(keys, value)
Set Methods
Set Operations
set.add(item)
set.remove(item)
set.discard(item)
set.pop()
set.clear()
set.copy()
set.union(other)
set.intersection(other)
set.difference(other)
set.symmetric_difference(other)
set.issubset(other)
set.issuperset(other)
set.isdisjoint(other)
Classes & Objects
Class Definition
# Basic class
class Person:
# Class variable
species = "Homo sapiens"
def __init__(self, name, age):
# Instance variables
self.name = name
self.age = age
def greet(self):
return f"Hello, I'm {self.name}"
def __str__(self):
return f"Person(name={self.name}, age={self.age})"
def __repr__(self):
return f"Person('{self.name}', {self.age})"
# Inheritance
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def study(self):
return f"{self.name} is studying"
Special Methods (Dunder Methods)
__init__(self)
__str__(self)
__repr__(self)
__len__(self)
__getitem__(self, key)
__setitem__(self, key, value)
__delitem__(self, key)
__contains__(self, item)
__iter__(self)
__next__(self)
__call__(self)
__enter__(self)
__exit__(self, exc_type, exc_val, exc_tb)
Exception Handling
Try-Except Blocks
# Basic exception handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
else:
print("No exceptions occurred")
finally:
print("This always executes")
# Raising exceptions
raise ValueError("Invalid value")
raise ValueError("Invalid value") from original_exception
# Custom exceptions
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
Common Exceptions
Exception
ValueError
TypeError
IndexError
KeyError
AttributeError
NameError
FileNotFoundError
ZeroDivisionError
ImportError
ModuleNotFoundError
RuntimeError
File I/O
File Operations
# Reading files
with open('file.txt', 'r') as f:
content = f.read() # Read entire file
lines = f.readlines() # Read all lines
line = f.readline() # Read one line
# Writing files
with open('file.txt', 'w') as f:
f.write("Hello, World!")
f.writelines(["Line 1\n", "Line 2\n"])
# Appending to files
with open('file.txt', 'a') as f:
f.write("Appended text")
# File modes
# 'r' - read (default)
# 'w' - write (overwrites)
# 'a' - append
# 'x' - exclusive creation
# 'b' - binary mode
# 't' - text mode (default)
# '+' - read and write
Modules & Packages
Import Statements
# Import entire module
import math
import os
# Import specific functions
from math import sqrt, pi
from os import path
# Import with alias
import numpy as np
from datetime import datetime as dt
# Import all (not recommended)
from math import *
# Relative imports (within packages)
from . import module
from ..parent import module
from .subpackage import module
Standard Library Modules
os - Operating system interface
sys - System-specific parameters
math - Mathematical functions
random - Random number generation
datetime - Date and time handling
json - JSON encoder/decoder
re - Regular expressions
collections - Specialized containers
itertools - Iterator functions
functools - Higher-order functions
pathlib - Object-oriented filesystem paths
urllib - URL handling modules