Python Fundamentals: Operators, Control Flow, Functions, Strings, and Data Structures
Python Operators & Evaluation Order
Arithmetic Operators:
Basic Operations: Addition (), Subtraction (), and Multiplication ().
True Division (): Always returns a floating-point number, even if numbers divide evenly (e.g., and ).
Floor Division (): Divides and rounds down toward negative infinity (to the left on the number line), rather than rounding toward zero.
Positive numbers simply drop the decimal: .
Negative results round further down away from zero: and .
Modulo (): Finds the remainder after floor division using the mathematical identity .
In Python, the remainder always shares the sign of the divisor ().
Examples: , whereas (calculated as ).
Exponentiation (): Calculates powers (e.g., ).
Operator Precedence (Order of Execution from Highest to Lowest):
Parentheses:
()— Always evaluated first to group operations.Exponentiation:
**— Evaluates right-to-left and binds tighter than unary negation (e.g., , not ; ).Unary Signs:
+x,-x— Positive or negative signs applied to a single number.Multiplication, Division, Floor Division, Modulo:
*,/,//,\%— Evaluated from left to right.Addition and Subtraction:
+,-— Evaluated from left to right.Comparison Operators:
<,<=,>,>=,==,!=— Evaluated after arithmetic.Boolean Logical Operators: Evaluated in order:
not, thenand, thenor.
Chained Comparisons:
Python allows comparisons to be linked smoothly. An expression like automatically evaluates as and simultaneously without requiring explicit
andstatements.
Boolean Logic & Short-Circuiting
Logical Operators:
not: Inverts the truth value (TruebecomesFalse). Has the highest logical precedence.and: Evaluates toTrueonly when both sides areTrue. It has medium precedence.or: Evaluates toTrueif at least one side isTrue. It has the lowest logical precedence.Precedence Rule: Because
andbinds tighter thanor, the expressiona or b and cis always evaluated asa or (b and c).
De Morgan's Laws:
Useful for simplifying negations of complex conditions:
not (p and q)is equivalent to(not p) or (not q).not (p or q)is equivalent to(not p) and (not q).Simple Rule: Distribute the
notto every condition, reverse the comparisons, and switchandtoor(or vice versa).
Short-Circuit Evaluation (Lazy Evaluation):
andShort-Circuit: If the left-hand condition isFalse, Python immediately stops and returnsFalsewithout checking the right-hand condition.orShort-Circuit: If the left-hand condition isTrue, Python immediately stops and returnsTruewithout checking the right-hand condition.The Safety Guard Pattern: Used to avoid crashes like division by zero or index errors:
x != 0 and 10 // x > 1: If , the left side isFalse, so the division step is never executed, preventing aZeroDivisionError.
Control Flow: Conditionals & Branching
Branching Rules:
Statements require a colon
:at the end of the line and an indented code block below.Execution proceeds strictly top-to-bottom. The program enters the first branch that evaluates to
True, runs its code, and exits the entire conditional structure.Specific to General: Always place the strictest (most specific) condition first. Broad conditions placed too early will swallow inputs meant for later branches (e.g., checking
score >= 50beforescore >= 80prevents the gradeAbranch from ever running).In an
if/elif/elseconstruct, at most one branch runs (exactly one if anelseis present).Separate
ifstatements start fresh checks, meaning multiple independent blocks can execute.
String Comparisons (Lexicographical / Dictionary Order):
Strings compare character-by-character using Unicode/ASCII numeric values.
Capital Letters Come First: All uppercase letters have lower numeric values than lowercase letters (e.g.,
"apple" < "Banana"evaluates toFalsebecause"B"comes before"a").Digit Characters Are Alphabetical: Strings of numbers compare character-by-character (e.g.,
"10" < "9"isTruebecause the character"1"comes before"9").Prefix Rule: If one string matches the start of another, the shorter string is smaller (e.g.,
"cat" < "catalog"isTrue).
Strings: Indexing, Slicing, and Immutability
Indexing Rules:
Positive indices start at from the left: .
Negative indices count backwards from the right: is the last character, is second-to-last.
Accessing an index that does not exist (such as
s[len(s)]) raises anIndexError.
Slicing Syntax (
s[start:stop:step]):Exclusion of
stop: The slice includes the character atstartand stops right beforestop. A slices[a:b]extracts exactly characters.Default Values: Omitting
startstarts at the beginning; omittingstopruns to the end.Step Direction:
A positive step moves forward.
A negative step moves backward (e.g.,
s[::-1]reverses the entire string).Error Safety: Unlike indexing, slicing out-of-bounds never crashes. Indices are automatically clipped to the boundaries of the string (e.g.,
s[10:]on a short word returns an empty string"").Mismatched Steps: If
start,stop, andstepcontradict each other (such ass[2:5:-1]), Python safely produces an empty string"".Chained Slicing: Read left-to-right; each slice operates on the newly generated substring from the previous slice.
Immutability (Read-Only Strings):
Strings cannot be altered in place. Assigning to an index (e.g.,
s[0] = "b") triggers aTypeError.To modify a string, you must build a new string using concatenation (
+), repetition (*), or slices (e.g.,"b" + s[1:]).
Functions, Return Mechanics, and Scope
Defining vs. Calling:
A
defblock merely registers instructions; nothing runs until the function is invoked by name with parentheses (e.g.,func()).Arguments are pass into parameters strictly by order/position, not by variable names used outside the function.
print()vs.return:print()displays a visual value to the screen and immediately throws it away; the program cannot reuse that data.returnsends a computed value back to the caller so it can be stored in a variable or used in an expression.returnexits the function immediately. Any code placed below an executedreturnstatement in the same block is unreachable.If a function finishes without reaching an explicit
return, it evaluates toNone.
Variable Scope (LEGB Hierarchy):
Python searches for variable names in four levels: Local, Enclosing, Global, Built-in.
Variables created or assigned inside a function belong exclusively to that specific function call (local scope) and vanish when it finishes.
A function can read global variables freely without special keywords.
The Local Assignment Rule: If a variable is assigned anywhere inside a function, Python marks that variable as local for the entire function. Attempting to read that variable before the assignment line causes an
UnboundLocalError.Modifying Globals: To modify a global variable from inside a function, it must be explicitly declared using the
globalkeyword (e.g.,global total).
Iteration: While Loops & For Loops
whileLoops (Conditional Loops):Best used when the number of iterations is unknown in advance.
Requires three structural components:
Initialization: Setting a starting value before the loop.
Condition Check: Evaluated before every single pass.
Update Step: Changing the tracking variable inside the body to move toward a terminating condition.
If the update step is missing or flawed, the condition remains
Trueforever, creating an infinite loop.
forLoops over Sequences:By Character (
for ch in s): Visits each character one-by-one from left to right. Ideal when only the characters themselves are needed.By Index (
for i in range(len(s))): Generates integer index positions. Ideal when character positions or adjacent elements are required.Look-Ahead Guard: When comparing adjacent elements (e.g.,
s[i] == s[i + 1]), stop the range atrange(len(s) - 1)so thati + 1does not step out-of-bounds on the final loop pass.
The
range()Function:range(stop): Produces values from up to .range(start, stop, step): Starts atstart, steps bystep, and excludesstop.
Standard Accumulation Patterns:
Counting: Set
count = 0before the loop; increment withcount += 1inside matching conditions.Building: Set
out = ""before the loop. Useout = out + chto build forwards, orout = ch + outto build backwards (reversing).Flags: Set
found = Falsebefore the loop. Flip tofound = Truewhen a target is found. Never add anelse: found = Falseinside the loop, or the flag will only reflect the very last item visited.
Lists: Mutability, Aliasing, and Best Practices
Lists vs. Strings:
Lists are ordered, mutable sequences (
[1, 2, 3]).In-Place Mutation: Lists can be changed directly in memory using index assignment (
L[1] = 7) orL.append(value)without creating a new list object.List Slicing: A slice of a list (
L[1:3]) copies the selected elements into a brand-new list.
Aliasing vs. Assignment:
Aliasing (
L2 = L1): Does not create a copy. Both variable names point to the exact same list in memory. Mutating the list viaL2immediately alters the list seen byL1.Reassignment (
L2 = [4, 5, 6]): Re-points the variableL2to an entirely new list object in memory, leavingL1unchanged.Making Independent Copies: To modify a list without affecting the original, clone it explicitly using
L.copy()or a full sliceL[:].
Lists Passed to Functions:
Passing a list to a function passes the reference to that object. In-place mutations (
L.append(val)orL[0] = val) permanently modify the caller's original list.Reassigning the parameter variable inside the function (e.g.,
L = [1, 2]) only changes the local pointer and does not touch the caller's original list.
Edge Cases & Iteration Hazards:
Never add or remove elements from a list while iterating over it directly with a
forloop, as this causes skipped elements and unexpected behavior.Guarding Averages Against
ZeroDivisionError: When calculating the average of filtered values, guard withif count == 0rather thanif total == 0, because valid collections can contain negative numbers that sum to (e.g.,[-2, 2]).
Formulas, mathematical identities, boundary rules, and precedence that you need to memorize:
1. Arithmetic & Remainder Formulas
Modulo (Remainder) Identity:
The Sign Rule: In Python, the modulo remainder always takes the sign of the divisor ().
Examples: , but (calculated as ).
Floor Division () Rule:
Divides and rounds down toward negative infinity (left on the number line), not toward zero.
Positive:
Negative: and
2. Slicing & Boundary Formulas
Slice Length Formula:
Slicing
s[start:stop]always includesstartand excludesstop.
Index Range:
Positive valid indices: to
Last valid index: (or )
Look-Ahead Range Boundary:
When comparing adjacent elements
s[i] == s[i + 1], the loop range formula must stop at:range(len(s) - 1)This ensures that never steps past the final index to raise an
IndexError.
3. Boolean Logic & De Morgan's Laws
De Morgan's Law for AND:
not (p and q)is mathematically equivalent to(not p) or (not q)De Morgan's Law for OR:
not (p or q)is mathematically equivalent to(not p) and (not q)Chained Comparisons Equivalence: is evaluated identically to
a < b and b < c
4. Operator Precedence Hierarchy (Highest to Lowest)
Parentheses:
()Exponentiation:
**(Evaluates right-to-left: ; )Unary Signs:
+x,-xMultiplication, Division, Floor Division, Modulo:
*,/,//,\%(Evaluated left-to-right)Addition & Subtraction:
+,-(Evaluated left-to-right)Comparison Operators:
<,<=,>,>=,==,!=Logical Operators:
not, thenand, thenor(a or b and ca or (b and c))
5. Essential Syntax Idioms & Safety Guards
Sequence Reversal:
s[::-1]Independent List Copy:
L.copy()orL[:](prevents unintended aliasing mutations)Average Calculation Safety Guard:
if count == 0: return 0.0Always guard with
count == 0rather thantotal == 0, because valid non-empty lists can sum to zero (e.g.,[-2, 2]).