Conditions and loops
AdvancedPrograms do not always run straight through: if lets them choose a path, loops let them repeat. These two make programs think and save work.
- if/else = choosing a path — the flowchart diamond in code
- == tests equality; = assigns
- for repeats a counted number of times; range(n) counts 0 to n-1
§Text Passage
1Conditions let a program choose a path: if a condition holds, do A, otherwise do B — like the everyday decision to take an umbrella when it rains. Loops make a program repeat tasks automatically, so the same code never has to be copied ten times, saving space and reducing mistakes. Together they are called control structures: they steer the flow of a program, form the core of programming thinking, and are the origin of the diamond and branch arrows in flowcharts.
2In Scratch, the 'if…then…else' block combines with the 'repeat' block; in Python you write if-else statements and for loops, and indentation marks which lines belong inside a condition or a loop — wrong indentation stops the program from running. Common exercises include printing the numbers 1 to 10 with a loop, testing whether a score is a pass, or combining the two to check every classmate's marks in turn.
3Hong Kong examples: the Octopus reader on a bus checks whether the balance is enough before deducting the fare, a lift moves floor by floor answering the buttons on each level, an MTR gate opens only after a successful ticket check, and an automatic door opens only when someone approaches — all applications of conditions and loops. These two structures are everywhere in daily life, and mastering them is a great leap forward in programming thinking.
1Summary 重點摘要
Programs do not always run straight through: if lets them choose a path, loops let them repeat. These two make programs think and save work.
2Vocabulary cards Vocabulary
A true/false statement, e.g. mark ≥ 50.
If true run part A, otherwise part B; Scratch says 'if…then…else'.
== equal, != not equal, > greater, < less, >= and <=.
Repeating a block of code; Scratch says 'repeat N'.
for i in range(5) in Python runs 5 times (i counts 0 to 4).
Python uses leading spaces to show which lines belong inside an if or loop; no indent, no work.
A loop that repeats while a condition stays true; the condition must be able to turn false or the loop never ends.
The operator giving a division's remainder, e.g. 7 % 2 = 1; remainder 0 means even.
3Step by step Steps
- Choosing a path: ifThe flowchart diamond becomes code: if. In Python, write if score >= 50: with an indented print('Pass') on the next line, then else: print('Fail'), and the program chooses a path by the score. In Scratch it is the 'if…then…else' block, with the condition fitted into the hexagon slot. Both tools share one logic: when the condition holds, take the first path; otherwise take the other. A beginner's common error is forgetting the colon at the end of the if line, and the program raises a syntax error at once.
- Comparison symbolsThere are only a few comparison symbols, yet they cause the most errors: the double equals == asks 'are these equal?'; the single equals = only puts something into a variable — the two are totally different. Greater than >, less than <, at least >=, at most <= work much like maths, and != means 'not equal'. Every comparison answers just True or False. A common mistake is using = where == is meant: if score = 50: raises a syntax error immediately — remember, 'to ask equality, write two'.
- Repeating: loopsRepeated work is handled by loops: Scratch offers the 'repeat 10' block, with the repeated blocks placed inside; Python writes for i in range(10): and the indented lines below repeat ten times. range(10) produces the ten numbers 0 to 9 — exactly ten repeats, which is the easiest point to get wrong, because many assume range(10) includes 10. To count from 1 to 10, write range(1, 11): the start is included, the end is not. A loop instead of ten copied lines saves space and prevents mistakes.
- Indentation rulesPython uses no brackets around the 'inside' code — it uses indentation, the spaces at the start of a line, usually four. Statements on the same level must align; lines under an if or for indent one more level. Get it wrong and the program either raises a SyntaxError and refuses to run, or, worse, runs but does the wrong thing — one extra space accidentally pulls a line inside a loop. Scratch expresses the same idea with the shapes of blocks: the deeper a block is nested, the more deeply it sits inside loops or conditions.
- The classic combo: for + ifTo print every even number from 1 to 10, combine a loop with a condition: the outer line for i in range(1, 11):, indented under it if i % 2 == 0:, and one more level in, print(i). The % symbol gives the remainder: i % 2 == 0 means i divided by 2 leaves 0 — that is, an even number. As it runs, the program tests each i in turn and prints only the ones that pass. This combo is a favourite exam question: to print multiples of 3 instead, change the condition to i % 3 == 0 and nothing else moves.
- while: keep going while truewhile suits tasks where the number of repeats cannot be known in advance: write while score < 100: and the indented code below keeps running until the condition turns false. Something inside the loop must eventually change the condition, e.g. score = score + 10; otherwise the condition stays true forever, the loop never ends, and the program hangs. For example, inputting scores until the total reaches a target fits while, because no one knows in advance how many inputs are needed. After writing a while, first check that one line inside changes the condition — that is the key to avoiding a freeze.
4Diagrams Diagrams
5Worked example Example
Example: what does this output? for i in range(3): with print(i) indented inside
- Break range(3) apart first: it produces the three numbers 0, 1 and 2, because Python counts from 0 and never includes the end value 3.
- The loop feeds each i to print in turn, so print runs three times, printing 0, 1 and 2 on separate lines.
- A common error is expecting 1, 2, 3; keep the rule 'starts at 0, end not included' in mind and the trap is avoided.
- Extension: to output 1, 2, 3, write range(1, 4) — the start 1 is included, the end 4 is not.
- Answer: It prints three lines: 0, 1, 2. The key is that range(3) starts at 0 and produces three numbers, not including 3 itself; to count 1 to 3, write range(1, 4), because a range always includes its start and excludes its end.
6Common mistakes Mistakes
7Quick check Quick check
Q1Which symbol tests equality in Python? A. = B. == C. =>
Q2How many times does for i in range(4) run?
Q3Explain if...else in plain words.
Q4Write the if line that checks whether score is 50 or above.
Q5Which Python line matches Scratch's 'repeat 10' block?
8Recap Recap
- if/else = choosing a path — the flowchart diamond in code
- == tests equality; = assigns
- for repeats a counted number of times; range(n) counts 0 to n-1
- Python indentation decides what is inside an if or loop
- for + if together: the loop checks each number, the condition picks the wanted ones