1.4.1 · D3Python & Scientific Computing

Worked examples — Python syntax, data types, control flow

2,466 words11 min readBack to topic

Before the table, three words we will lean on:


The scenario matrix

Each row is a class of situation this topic can throw at you. The last column names the worked example that nails it.

# Case class The tricky edge Covered by
A Division: sign & type / vs // vs %, positive operands Example 1
B Division: negative operand floor rounds down, not toward zero Example 2
C Division by zero (degenerate) raises an exception, not inf Example 3
D Type mixing / coercion int + float, str + int fails Example 4
E Truthiness: empty / zero / None [], 0, None, "" all falsy Example 5
F Reference vs copy (mutation trap) aliasing changes the "original" Example 6
G range boundaries (batching) start, stop-exclusive, step Example 7
H Scope (LEGB) shadowing local name hides global Example 8
I Word problem (real ML) steps-per-epoch, last partial batch Example 9
J Exam twist (chained everything) comprehension + % + truthiness Example 10

We now walk every cell.


The division trio: /, //, %

Before any example, earn the three symbols on one picture.

Figure — Python syntax, data types, control flow

Why do we even need //? Because in ML you count discrete things — number of training steps, batch indices. You cannot run steps. // answers a counting question; / answers a measuring question.



Figure — Python syntax, data types, control flow




Figure — Python syntax, data types, control flow





Recall Rapid self-check

1000 // 32 and 1000 % 32 ::: 31 and 8 -7 // 2 in Python ::: -4 (rounds toward ) Value of 1000 // 0 ::: raises ZeroDivisionError int(3.7) vs round(3.7) ::: 3 (truncate) vs 4 (round) Is [0] truthy? ::: Yes — it has length 1, not empty After b = a; b[0]=9, what is a[0]? ::: 9 (same list, shared reference) list(range(0,100,32)) ::: [0, 32, 64, 96] Which values are falsy? ::: [], 0, 0.0, "", None, {}

See also: Python functions and lambda, Python iterators and generators, Pandas DataFrames, Object-oriented programming in Python, TensorFlow and PyTorch basics.