InterviewPrepKit

Home / Cheat Sheet / Algorithms & Data Structures with Python

Cheat sheet

Control Flow: if, for, while

Read the full lesson →

Control flow lets a program choose which code to run and repeat work, instead of running top to bottom once.

Boolean conditions

  • Comparisons produce True/False: <, >, == (equal?), != (different?), <=, >=.
  • == compares; = assigns. if x = 5: is a SyntaxError.
  • Combine with and (both), or (either), not (flip).

if / elif / else

  • if condition: runs its indented block only when the condition is True.
  • elif adds more cases checked in order; else is the catch-all.
  • Python runs the first true branch and skips the rest.
  • Indentation (4 spaces) is the grouping — no braces. Wrong indentation is an error.
score >= 90 ? --True--> "A"
     |False
score >= 80 ? --True--> "B"
     |False
score >= 70 ? --True--> "C"
     |False
             --------> "below C"

for loops

  • Runs the block once per item: for item in sequence:. One pass is an iteration.
  • range(n) gives 0 .. n-1; range(start, stop, step) stops before stop; negative step counts down.
  • range is O(1) space — it yields numbers on demand, not a list.
  • enumerate(seq) unpacks index, value each pass, so no manual counter.

while loops

  • Repeats as long as the condition stays true; checked before each pass.
  • The block must move the condition toward False (e.g. count = count - 1).
  • Forgetting that update = infinite loop (the classic while bug); Ctrl+C stops a hung program.

break, continue, nesting

  • break exits the loop immediately.
  • continue skips the rest of the current iteration, jumps to the next.
  • Inner loop runs fully on each outer pass; two loops over size n is O(n squared).

Gotchas

  • range stops one early: range(1, 5) = 1,2,3,4. Go one past to include a value.
  • range(5, 1) yields nothing, so the loop body never runs — check bounds.
  • Don’t add/remove items from a list while looping over it; loop a copy or build a new list.
  • In a branching test like FizzBuzz, check the combined case (% 3 and % 5) first.
Want the full picture? The lesson has the derivations, worked examples, and diagrams this card compresses into bullets. Read the full lesson →
Report a bug