Quiz
Warm-up from lesson 8-3: in checkout, `if not cart:` was true when cart was what?
Loop like a local
These idioms exist because Python is read far more often than it is written: teams standardize on them, reviewers expect them, and interviewers quietly grade on them. Each one replaces bookkeeping with stated intent.
Three rewrites cover most unpythonic loops.
Need the index too? enumerate, never range(len(...)):
for i, word in enumerate(words, start=1): print(i, word)
Two sequences in step? zip:
for name, score in zip(names, scores): print(name, score)
Multiple assignment by unpacking:
low, high = high, low # swap, no temp variable first, *rest = [1, 2, 3, 4] # first=1, rest=[2, 3, 4]
And truthiness: empty string, empty list, empty dict, 0, and None are all falsy, so write if items: rather than if len(items) > 0:. One exception: to distinguish None from empty, compare is None explicitly, as in the lesson 2-2 sentinel.
Code exercise · python
Run this program. enumerate, zip, unpacking, and a truthiness guard, all in twelve lines.
Small habits, big readability
- Chained comparisons:
if 0 <= i < len(xs):reads like math and replaces two clauses joined byand. - f-strings for all formatting:
f"{price:.2f}"renders 2 decimal places,f"{count:>5}"right-aligns in 5 columns. - dict.get(key, default) instead of checking
inbefore reading. - EAFP ("easier to ask forgiveness than permission"): Python style prefers trying the operation and catching the specific exception (lesson 8-3) over pre-checking every condition.
None of these change what your program can do. They change how fast the next human, often future you, can read it. That is worth real money in code review.
Code exercise · python
Your turn. Print each product's line as "name: $price" with exactly 2 decimals, numbered from 1 with enumerate, using zip over the two lists.
Code exercise · python
Your turn, two micro-reps. 1) Swap a and b in ONE line with no temp variable, then print them. 2) Print xs[i] only if i is a valid index, using ONE chained comparison instead of two conditions joined by and.
Quiz
Which is the most Pythonic way to loop with indexes over words?