PCEP cheat sheet
PCEP · Keep the key ideas within reach.
Computer Programming and Python Fundamentals
Python is interpreted and dynamically typed: no declaration is needed before a name is assigned, and a name can later be rebound to an object of a different type.
input() always returns a str, even when the user types digits; convert with int() or float() before arithmetic, otherwise + concatenates text.
print() separates arguments with a space and ends with a newline by default; the keyword arguments sep and end override those two behaviours.
Identifiers may contain letters, digits and underscores but cannot start with a digit; they are case-sensitive and cannot be keywords such as for, class or None.
Operators: / is true division and always returns float, // is floor division, % returns a remainder whose sign follows the divisor, ** is exponentiation and is right-associative.
Integer literal prefixes: 0b binary, 0o octal, 0x hexadecimal; underscores may separate digits (1_000_000) and do not affect the value.
None is a singleton of type NoneType meaning the absence of a value; identity test is 'x is None', not 'x == None'.
Precedence from highest: ** then unary + and -, then * / // %, then + and -, then comparisons, then not, then and, then or.
Comments begin with # and run to end of line; Python has no block comment syntax, though a triple-quoted string is often used as a stand-in.
Control Flow: Conditional Blocks and Loops
if/elif/else tests conditions top to bottom and executes only the first true branch; elif conditions are not evaluated once an earlier branch has run.
Blocks are defined by indentation (conventionally 4 spaces); inconsistent indentation raises IndentationError, and mixing tabs with spaces raises TabError.
Falsy values: 0, 0.0, 0j, '', [], (), {}, set(), None and False; every other object, including non-empty containers, evaluates as true.
range(stop) starts at 0, range(start, stop) and range(start, stop, step) exclude stop; a negative step counts downward and step=0 raises ValueError.
break exits the innermost enclosing loop immediately; continue skips the rest of the current iteration; pass is a no-op placeholder statement.
The else block of a for or while loop runs only when the loop ends without executing break.
Chained comparisons such as 0 <= x < 10 mean 0 <= x and x < 10, with the middle operand evaluated only once.
Conditional expression: value_if_true if condition else value_if_false; it is an expression and must yield a value, unlike an if statement.
Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings
Lists are mutable and ordered and allow duplicates: index with list[i], negative indices count from the end, and slicing [start:stop:step] returns a new list.
Tuples are immutable sequences; a one-element tuple needs a trailing comma - (1,) is a tuple while (1) is an int.
Sets are unordered collections of unique hashable elements: create an empty one with set(), because {} builds an empty dict, and indexing is not supported.
Dicts map hashable keys to values and preserve insertion order; d[key] raises KeyError when absent, while d.get(key, default) returns default instead.
Strings are immutable: upper(), lower(), strip(), replace(), split() and join() return new objects; assigning to s[0] raises TypeError.
List mutation methods: append(x) adds one element, extend(iterable) adds each item, insert(i, x) shifts the rest, pop() removes by index, remove() removes the first matching value.
Set operators: | union, & intersection, - difference, ^ symmetric difference; the operators require sets on both sides, while the named methods accept any iterable.
len(), in and not in work for lists, tuples, sets, dicts (key membership) and strings (substring membership); sorted() returns a new list from any iterable.
Repeating a nested list with [[0]*3]*3 creates three references to one inner list, so use a comprehension such as [[0]*3 for _ in range(3)] instead.
Functions and Exceptions
def name(parameters): defines a function; return without a value, or falling off the end of the body, both return None.
Default parameter values are evaluated once when the def statement executes, so a mutable default like [] is shared across every call.
Positional arguments must precede keyword arguments; *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict.
Name resolution follows LEGB: Local, Enclosing function, Global, Built-in; assigning a name inside a function makes it local unless global or nonlocal is declared.
try/except/else/finally: except runs on a matching exception, else runs only if no exception occurred, and finally always runs.
except SomeError as e binds the exception object; a bare except: also catches KeyboardInterrupt and SystemExit, so naming the exception type is safer.
raise ValueError('message') raises an exception; uncaught exceptions propagate up the call stack until a matching handler is found.
Frequent built-ins: ValueError, TypeError, KeyError, IndexError, ZeroDivisionError, NameError, FileNotFoundError, AttributeError.
lambda parameters: expression builds an anonymous function whose body is a single expression whose value is returned; it cannot contain statements.
File Handling and Module Imports
open(path, mode) modes: 'r' read (default), 'w' truncate or create, 'a' append, 'x' exclusive create that fails if the file exists, plus 'b' binary, 't' text and '+' read/write.
with open(path) as f: closes the file automatically, even if an exception is raised inside the block, replacing a manual try/finally close.
Reading: f.read() returns the whole file as one string, f.readline() returns one line including '\n' (or '' at end of file), f.readlines() returns a list of lines, and iterating over f yields lines.
f.write(s) writes a string and returns the number of characters written; it adds no newline, and writelines() writes each string of an iterable without adding separators.
Text mode returns str, binary mode ('rb') returns bytes; a file opened for writing with 'w' must be closed or flushed before its content is guaranteed on disk.
Import styles: import math then math.sqrt(16); from math import sqrt then sqrt(16); import math as m then m.sqrt(16); from math import * imports all public names.
An import executes the module's top-level code only the first time; later imports reuse the cached module object held in sys.modules.
if name == 'main': guards code that should run only when the file is executed directly, not when it is imported as a module.
The random module provides random(), randint(a, b) with both bounds included, randrange(), choice() and seed() for reproducible sequences.