Please wait
Please wait
Comprehensive Python programming reference guide covering syntax, data structures, functions, OOP, and more. Essential Python commands and examples for quick reference.
Python variable assignment and basic data types
basicsPython is dynamically typed. You don't need to declare variable types.
# Variable assignment
name = "Python"
age = 30
price = 99.99
is_active = True
# Multiple assignment
x, y, z = 1, 2, 3
# Type checking
type(name) # <class 'str'>
type(age) # <class 'int'>String operations and methods
basicsPython strings are immutable and support various operations including slicing, formatting, and methods.
# String basics
s = "Hello World"
len(s) # 11
s[0] # 'H'
s[-1] # 'd'
s[0:5] # 'Hello'
s[::-1] # 'dlroW olleH'
# String methods
s.upper() # 'HELLO WORLD'
s.lower() # 'hello world'
s.replace("H", "J") # 'Jello World'
s.split() # ['Hello', 'World']
s.strip() # Removes whitespace
# String formatting
name = "John"
f"Hello {name}" # f-string (Python 3.6+)
"Hello {}".format(name) # format methodList operations, methods, and comprehensions
data-structuresLists are mutable ordered collections. List comprehensions provide a concise way to create lists.
# List basics
my_list = [1, 2, 3, 4, 5]
my_list.append(6) # [1, 2, 3, 4, 5, 6]
my_list.insert(0, 0) # [0, 1, 2, 3, 4, 5, 6]
my_list.pop() # Removes and returns 6
my_list.remove(0) # Removes first 0
my_list.sort() # Sorts in place
my_list.reverse() # Reverses in place
# List slicing
my_list[1:3] # [2, 3]
my_list[:3] # [1, 2, 3]
my_list[2:] # [3, 4, 5]
# List comprehensions
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]
nested = [[x*y for y in range(3)] for x in range(3)]
# [[0, 0, 0], [0, 1, 2], [0, 2, 4]]Dictionary operations and methods
data-structuresDictionaries are key-value pairs. Keys must be immutable types (strings, numbers, tuples).
# Dictionary basics
person = {
"name": "John",
"age": 30,
"city": "NYC"
}
# Accessing values
person["name"] # 'John'
person.get("name") # 'John' (safer)
person.get("email", "N/A") # Returns default if key missing
# Modifying
person["age"] = 31
person["email"] = "john@example.com" # Add new key
person.pop("email") # Remove and return value
del person["city"] # Remove key
# Dictionary methods
person.keys() # dict_keys(['name', 'age'])
person.values() # dict_values(['John', 31])
person.items() # dict_items([('name', 'John'), ...])
# Dictionary comprehension
squares_dict = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}Tuple and set operations
data-structures# Tuples (immutable)
tuple1 = (1, 2, 3)
tuple2 = 1, 2, 3 # Parentheses optional
x, y, z = tuple1 # Unpacking
# Tuple methods
my_tuple = (1, 2, 2, 3)
my_tuple.count(2) # 2
my_tuple.index(3) # 3
# Sets (unordered, unique elements)
my_set = {1, 2, 3, 4}
my_set.add(5) # Add element
my_set.remove(2) # Remove (raises KeyError if missing)
my_set.discard(2) # Remove (no error if missing)
# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1 | set2 # Union: {1, 2, 3, 4, 5}
set1 & set2 # Intersection: {3}
set1 - set2 # Difference: {1, 2}
set1 ^ set2 # Symmetric difference: {1, 2, 4, 5}Conditionals, loops, and control statements
basicsPython uses indentation for code blocks. Control flow includes if/elif/else, for/while loops, and break/continue statements.
# If/elif/else
age = 20
if age < 18:
print("Minor")
elif age < 65:
print("Adult")
else:
print("Senior")
# Ternary operator
status = "adult" if age >= 18 else "minor"
# For loops
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for item in [1, 2, 3]:
print(item)
# Enumerate
for index, value in enumerate(["a", "b", "c"]):
print(index, value) # 0 a, 1 b, 2 c
# While loop
count = 0
while count < 5:
print(count)
count += 1
if count == 3:
break # Exit loop
if count == 2:
continue # Skip rest of iterationFunction definition, arguments, and advanced features
functionsFunctions are first-class objects in Python. They support default arguments, *args, **kwargs, lambda expressions, and decorators.
# Basic function
def greet(name):
return f"Hello, {name}"
# Default arguments
def power(base, exponent=2):
return base ** exponent
power(3) # 9
power(3, 3) # 27
# *args and **kwargs
def func(*args, **kwargs):
print(args) # Tuple of positional args
print(kwargs) # Dict of keyword args
func(1, 2, 3, name="John", age=30)
# Lambda functions
square = lambda x: x ** 2
add = lambda x, y: x + y
# Map, filter, reduce
numbers = [1, 2, 3, 4, 5]
map(lambda x: x**2, numbers) # Map
filter(lambda x: x % 2 == 0, numbers) # Filter
from functools import reduce
reduce(lambda x, y: x + y, numbers) # Reduce
# Function annotations (type hints)
def add(a: int, b: int) -> int:
return a + bComprehensive guide to comprehensions
data-structuresCreate lists concisely: [expression for item in iterable]
Create dictionaries: {key: value for item in iterable}
Create sets: {expression for item in iterable}
Comprehensions are more Pythonic and often faster than loops for simple transformations.
Reading and writing files
io# Reading files
with open("file.txt", "r") as f:
content = f.read()
lines = f.readlines()
for line in f: # Iterate line by line
print(line)
# Writing files
with open("file.txt", "w") as f:
f.write("Hello World")
f.writelines(["Line 1\n", "Line 2\n"])
# Appending
with open("file.txt", "a") as f:
f.write("New line")
# File modes
# "r" - read (default)
# "w" - write (overwrites)
# "a" - append
# "x" - exclusive creation
# "b" - binary mode
# "t" - text mode (default)
# JSON files
import json
with open("data.json", "r") as f:
data = json.load(f)
with open("data.json", "w") as f:
json.dump(data, f, indent=2)Classes, inheritance, and OOP concepts
oopPython supports OOP with classes, inheritance, encapsulation, and polymorphism. Special methods (dunder methods) allow operator overloading.
# Basic class
class Person:
# Class attribute
species = "Homo sapiens"
# Constructor
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age
# Instance method
def introduce(self):
return f"I'm {self.name}, {self.age} years old"
# Class method
@classmethod
def from_birth_year(cls, name, birth_year):
age = 2024 - birth_year
return cls(name, age)
# Static method
@staticmethod
def is_adult(age):
return age >= 18
# 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)
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
def __repr__(self):
return f"Vector({self.x}, {self.y})"Try/except blocks and exception handling
basics# Basic try/except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
# Multiple exceptions
try:
value = int("abc")
result = 10 / value
except ValueError:
print("Invalid number")
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print(f"Error: {e}")
# Else and finally
try:
file = open("file.txt")
data = file.read()
except FileNotFoundError:
print("File not found")
else:
print("File read successfully")
finally:
file.close() # Always executes
# Raising exceptions
if age < 0:
raise ValueError("Age cannot be negative")
# Custom exceptions
class CustomError(Exception):
pass
raise CustomError("Something went wrong")
# Exception chaining
try:
process_data()
except ValueError as e:
raise RuntimeError("Processing failed") from eImporting modules and creating packages
basicsUse import module, from module import function, or import module as alias
Pattern matching with re module
text-processingimport re
# Basic patterns
pattern = r"\d+" # One or more digits
text = "Price is 100 dollars"
match = re.search(pattern, text)
if match:
print(match.group()) # "100"
# Common patterns
re.findall(r"\d+", text) # Find all: ["100"]
re.sub(r"\d+", "X", text) # Replace: "Price is X dollars"
re.split(r"\s+", text) # Split: ["Price", "is", "100", "dollars"]
# Pattern flags
re.search(r"hello", text, re.IGNORECASE)
re.search(r"^start", text, re.MULTILINE)
# Groups
pattern = r"(\d{3})-(\d{3})-(\d{4})"
phone = "123-456-7890"
match = re.search(pattern, phone)
match.group(1) # "123"
match.groups() # ("123", "456", "7890")
# Named groups
pattern = r"(?P<area>\d{3})-(?P<exchange>\d{3})"
match = re.search(pattern, phone)
match.group("area") # "123"Generator functions and iterator protocol
advancedGenerators are memory-efficient iterators created with yield. They produce values lazily, one at a time.
# Generator function
def countdown(n):
while n > 0:
yield n
n -= 1
for num in countdown(5):
print(num) # 5, 4, 3, 2, 1
# Generator expression
squares = (x**2 for x in range(10))
next(squares) # 0
next(squares) # 1
# Iterator protocol
class Counter:
def __init__(self, low, high):
self.low = low
self.high = high
def __iter__(self):
return self
def __next__(self):
if self.low > self.high:
raise StopIteration
self.low += 1
return self.low - 1
for num in Counter(1, 5):
print(num) # 1, 2, 3, 4, 5Function decorators and their uses
advanced# Simple decorator
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# Output:
# Before function call
# Hello!
# After function call
# Decorator with arguments
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}")
# Built-in decorators
class MyClass:
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@staticmethod
def static_method():
return "Static"
@classmethod
def class_method(cls):
return clsUsing with statements and creating custom context managers
advancedThe with statement ensures proper resource cleanup. Files, database connections, and locks use context managers.
Use __enter__ and __exit__ methods, or the @contextmanager decorator from contextlib.
Comprehensive list methods reference
data-structuresmy_list = [1, 2, 3]
# Adding elements
my_list.append(4) # [1, 2, 3, 4]
my_list.extend([5, 6]) # [1, 2, 3, 4, 5, 6]
my_list.insert(0, 0) # [0, 1, 2, 3, 4, 5, 6]
# Removing elements
my_list.remove(0) # Remove first occurrence
my_list.pop() # Remove and return last
my_list.pop(0) # Remove at index
my_list.clear() # Empty the list
# Finding elements
my_list.index(3) # Returns index of first occurrence
my_list.count(2) # Count occurrences
3 in my_list # True
# Sorting and reversing
my_list.sort() # Sort in place
my_list.sort(reverse=True) # Descending
sorted(my_list) # Returns new sorted list
my_list.reverse() # Reverse in place
reversed(my_list) # Returns iterator
# List concatenation
list1 + list2 # Concatenate
list1 * 3 # Repeat list 3 timesComprehensive dictionary methods
data-structuresd = {"a": 1, "b": 2, "c": 3}
# Accessing
value = d["a"] # Get value (KeyError if missing)
value = d.get("a") # Safe get (None if missing)
value = d.get("a", 0) # With default
value = d.setdefault("d", 4) # Set if missing, return value
# Updating
d.update({"e": 5}) # Merge dictionaries
d |= {"f": 6} # Python 3.9+ merge operator
# Removing
del d["a"] # Remove key
d.pop("b") # Remove and return value
d.popitem() # Remove and return (key, value)
d.clear() # Empty dictionary
# Views (Python 3)
d.keys() # dict_keys view
d.values() # dict_values view
d.items() # dict_items view
# Dictionary methods
len(d) # Number of keys
"a" in d # Check key existence
# Copying
d2 = d.copy() # Shallow copy
d3 = dict(d) # Shallow copy
from copy import deepcopy
d4 = deepcopy(d) # Deep copyDifferent string formatting methods
basicsname = "John"
age = 30
# f-strings (Python 3.6+, recommended)
f"Hello, {name}" # 'Hello, John'
f"Age: {age + 5}" # 'Age: 35'
f"{name:>10}" # Right align
f"{name:<10}" # Left align
f"{age:05d}" # Zero-padded: '00030'
f"{3.14159:.2f}" # 2 decimals: '3.14'
# .format() method
"Hello, {}".format(name)
"Hello, {name}".format(name=name)
"{0} is {1}".format(name, age)
"{name:>10}".format(name=name)
# % formatting (old style)
"Hello, %s" % name
"%s is %d" % (name, age)
# Template strings
from string import Template
t = Template("Hello, $name")
t.substitute(name=name)Advanced collection types
data-structuresThese specialized collections provide efficient solutions for common problems.
datetime module usage
iofrom datetime import datetime, date, time, timedelta
# Current date/time
now = datetime.now()
today = date.today()
# Creating dates
birthday = date(1990, 5, 15)
meeting = datetime(2024, 12, 25, 14, 30)
# Formatting
now.strftime("%Y-%m-%d %H:%M:%S") # "2024-12-20 14:30:00"
datetime.strptime("2024-12-20", "%Y-%m-%d")
# Time delta
future = now + timedelta(days=7)
past = now - timedelta(hours=24)
difference = future - now # Returns timedelta
print(difference.days) # 7
print(difference.seconds) # Seconds component
# Timezone (Python 3.2+)
from datetime import timezone
dt = datetime.now(timezone.utc)
# Using pytz (third-party)
import pytz
tz = pytz.timezone("US/Eastern")
dt_eastern = datetime.now(tz)