Python Reference
0. Basics
0.1 Hello World
# print() adds a newline by default
print("Hello, World!")
TERMINAL OUTPUT
Hello, World!
0.2 Building & Running
Python is interpreted. Use the python3
command to execute scripts.
# Run a Python script directly
python3 main.py
TERMINAL OUTPUT
Hello, World!
0.3 Comments
# Single-line comment for brief notes
""" Multi-line
comment block or Docstring for documentation """
TERMINAL OUTPUT
(No output)
0.4 Imports
import sys # System-specific parameters and functions
import os # Miscellaneous operating system interfaces
from datetime import datetime # Import specific class from module
from math import pi as PI_CONST # Aliasing for shorter access
TERMINAL OUTPUT
(No output)
0.5 Exit Codes
import sys
# exit(0) for success, non-zero for error (e.g., 1)
sys.exit(1)
TERMINAL OUTPUT
(Process exits with status 1)
0.6 Error Handling
try:
# Attempt division by zero
result = 10 / 0
except ZeroDivisionError as e:
# Catch and print the specific error
print(f"Error: {e}")
finally:
# Always executed regardless of exception
print("Cleanup")
TERMINAL OUTPUT
Error: division by zero
Cleanup
1. Environment, Variables & Time
1.1 Variable Declaration
Dynamic typing; no explicit declaration keyword needed.
x = 5 # Integer
name = "Python" # String
MAX_VAL = 100 # Constant by convention (capitalized)
TERMINAL OUTPUT
(No output)
1.2 Integer Types & Limits
Python integers have arbitrary precision.
import sys
# Max size of a signed word on the current platform
print(sys.maxsize)
TERMINAL OUTPUT
9223372036854775807 (example)
1.3 Casting
Explicit conversion using type constructor functions.
i = int(3.14) # Float to int (3)
f = float("1.23") # String to float (1.23)
s = str(100) # Int to string ("100")
TERMINAL OUTPUT
(No output)
1.4 Environment Variables
import os
# Retrieve environment variable value
path = os.getenv("PATH")
# Set environment variable for current process
os.environ["API_KEY"] = "secret"
TERMINAL OUTPUT
(No output)
1.5 Time Measurement & Formatting
import time
from datetime import datetime
# Performance measurement using monotonic clock
start = time.perf_counter()
elapsed = time.perf_counter() - start
# Time formatting
now = datetime.now()
print(now.isoformat()) # ISO 8601 representation
print(now.strftime("%Y-%m-%d %H:%M:%S")) # Custom format
TERMINAL OUTPUT
2024-05-16T12:00:00.000000 (example)
2024-05-16 12:00:00 (example)
2. Operators & Regex
2.1 Arithmetic & Logic
a = 10 / 3 # True division (3.333)
b = 10 // 3 # Floor division (3)
c = 10 ** 3 # Power operator (1000)
d = True and False # Logical AND (False)
TERMINAL OUTPUT
(No output)
2.2 Regex & Pattern Matching
Using the standard library re module.
import re
text = "The price is $100"
# Search for pattern in text
match = re.search(r"\$(\d+)", text)
if match:
print(match.group(1)) # Print first captured group: "100"
TERMINAL OUTPUT
100
3. Argument Parsing
3.1 Argument Parsing
Standard library argparse for robust CLI
interfaces.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", action="store_true") # Boolean flag
parser.add_argument("-o", "--output", required=False) # Optional valued argument
parser.add_argument("input", help="Source file") # Mandatory positional argument
# Parse arguments from sys.argv
# args = parser.parse_args()
TERMINAL OUTPUT
(No output)
4. Functions & Memory
4.1 Declaration & Returns
def add(a, b=0):
"""Function with optional parameter and docstring"""
return a + b
# Multi-return via implicit Tuple packing/unpacking
def get_status():
return 200, "OK"
code, msg = get_status()
TERMINAL OUTPUT
(No output)
4.2 References & Pointers
Python passes objects by reference. Primitives (ints, strings) are immutable.
def modify(l):
# Modifies the original list object in place
l.append(4)
my_list = [1, 2, 3]
modify(my_list) # my_list is now [1, 2, 3, 4]
TERMINAL OUTPUT
(No output)
5. Control Flow
5.1 Conditionals (If/Else)
Standard branching logic. Python uses if,
elif, and else.
x = 10
if x > 5:
print("Greater")
elif x == 5:
print("Equal")
else:
print("Less")
TERMINAL OUTPUT
Greater
5.2 Switch / Case
Modern Python (3.10+) uses the match
keyword. For older versions, use
if/elif/else.
val = 2
match val:
case 1:
print("One")
case 2 | 3:
print("Two or Three")
case _:
print("Other")
TERMINAL OUTPUT
Two or Three
5.3 Basic Loops (While/For)
Iterative execution using while or
range-based for.
# Range-based for loop (0 to 2)
for i in range(3):
print(f"for: {i}")
x = 0
while x < 3:
print(f"while: {x}")
x += 1
TERMINAL OUTPUT
for: 0
for: 1
for: 2
while: 0
while: 1
while: 2
5.4 Breaking & Continue
Controlling loop flow.
for x in range(10):
if x < 2: continue # Skip iteration
if x == 5: break # Exit loop
print(x)
TERMINAL OUTPUT
2
3
4
5.5 Iterating Collections
Accessing items in lists or dictionaries.
# Iterating over List
for val in [10, 20]:
print(val)
# Iterating over Dictionary items
for k, v in {"a": 1}.items():
print(f"{k}: {v}")
TERMINAL OUTPUT
10
20
a: 1
6. Strings & Files
6.1 String Manipulation
s = " hello "
s = s.strip().capitalize() # Remove whitespace and uppercase first letter: "Hello"
sub = s[0:2] # String slice: "He"
joined = "-".join(["a", "b"]) # Join list into string: "a-b"
TERMINAL OUTPUT
(No output)
6.2 Path Joining
import os
from pathlib import Path
# Legacy OS-specific path joining
p1 = os.path.join("/", "usr", "bin")
# Modern object-oriented path handling
p2 = Path("/") / "usr" / "bin"
TERMINAL OUTPUT
(No output)
6.3 Streaming I/O (Chunks)
# Open binary file for reading
with open("data.bin", "rb") as f:
# Read in fixed-size chunks
while chunk := f.read(4096):
# Process the binary chunk
pass
TERMINAL OUTPUT
(No output)
6.4 Read to Memory
# Open text file using context manager
with open("file.txt", "r") as f:
# Read entire content into memory as string
content = f.read()
TERMINAL OUTPUT
(No output)
7. Binary & Bitwise
7.1 Allocation & Packing
import struct
# Create mutable bytearray buffer
buf = bytearray(12)
# Pack values into buffer: ! (Big-Endian), i (int32), d (double)
struct.pack_into("!id", buf, 0, 42, 3.14)
TERMINAL OUTPUT
(No output)
7.2 Bitwise Operations
res = 0b1010 & 0b1100 # Bitwise AND
res = 0b1010 | 0b1100 # Bitwise OR
res = 0b1010 ^ 0b1100 # Bitwise XOR
res = ~0b1010 # Bitwise NOT (complement)
res = 0b0001 << 2 # Bitwise Shift Left (0b0100)
TERMINAL OUTPUT
(No output)
7.3 Hex Conversion
# Format integer as hex string
s = hex(255) # "0xff"
# Parse hex string to integer
val = int("ff", 16) # 255
TERMINAL OUTPUT
(No output)
8. Collections & JSON
8.1 Lists, Maps & Sets
l = [1, 2]; l.append(3) # Dynamic List (append)
d = {"k": "v"}; val = d["k"] # Dictionary (Key access)
s = {1, 1, 2} # Set (Automatic deduplication: {1, 2})
TERMINAL OUTPUT
(No output)
8.2 JSON Parsing
import json
# Parse JSON string into Python dictionary
data = json.loads('{"id": 42}')
# Serialize Python dictionary to JSON string
s = json.dumps(data)
TERMINAL OUTPUT
(No output)
9. Systems & Networking
9.1 TCP Server & Client
import socket
# TCP Server setup
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind(('0.0.0.0', 8080)); srv.listen(1)
# TCP Client request
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect(("example.com", 80))
s.sendall(b"GET / HTTP/1.0\r\n\r\n")
TERMINAL OUTPUT
(No output)
9.2 UDP Server & Client
import socket
# Create UDP socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Send datagram without connection
s.sendto(b"ping", ("127.0.0.1", 8080))
TERMINAL OUTPUT
(No output)
9.3 Concurrency
import threading
def fn(): print("Task running")
# Spawn and start a background thread
t = threading.Thread(target=fn)
t.start(); t.join()
TERMINAL OUTPUT
Task running
9.4 SQLite
import sqlite3
# Connect to an in-memory database
db = sqlite3.connect(":memory:")
# Execute DDL command
db.execute("CREATE TABLE t(id)")
# Execute query and fetch result
res = db.execute("SELECT 42").fetchone()
print(res[0])
TERMINAL OUTPUT
42