الشروط والتكرار في بايثون

Computer Science · Key Stage 3 · The School

Decisions with if

Python chooses paths with if/elif/else, and the indented block below each is what runs: if score >= 50: → (indent) print("Pass") → else: → (indent) print("Retry"). Comparisons use == (equals), != (not equal), <, >, <=, >=. The indentation is not decoration — Python reads it as structure.

Two kinds of loop

for i in range(5): repeats its block 5 times with i counting 0,1,2,3,4 — use it when you know HOW MANY times. while lives < 3: repeats while a condition stays true — use it when you know WHEN TO STOP. A while whose condition never turns false runs forever: the infinite-loop bug every programmer writes once.

Tracing by hand

To predict a loop, make a table of the variables per pass. total = 0 → for i in range(4): total = total + i. Passes: i=0 total=0; i=1 total=1; i=2 total=3; i=3 total=6. Final total: 6. Tracing on paper is how you debug code you cannot yet "see" — and how exams test understanding.

The two errors everyone writes first

One: a single equals sign in a condition. `if score = 50:` does not compare anything, it tries to ASSIGN, and Python refuses with a syntax error. `==` asks a question, `=` gives an order. Two: off-by-one in range(). `range(5)` counts 0, 1, 2, 3, 4 — five numbers, ending at four — so `for i in range(1, 5)` runs four times, not five. If you want 1 to 5 inclusive, write `range(1, 6)`. Then a nested loop, which is where tracing earns its keep: `for i in range(3): for j in range(2): print(i, j)` prints six lines, because the INNER loop runs completely for each single pass of the outer one. Trace it as a table and the order is obvious; guess at it and it is not.

The School — all subjects · Knowledge map