Conditions and loops

Advanced

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.

For:Secondary 1 Information & Communication Technology · Unit:Coding basics · Lesson 10 of 13 in the learning path

After this lesson, you can:
  • 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
資訊及通訊科技Information & Communication Technology
Before this lesson you should know: Python basics: your first line of code

§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

C
Condition條件

A true/false statement, e.g. mark ≥ 50.

i
if...else如果…否則

If true run part A, otherwise part B; Scratch says 'if…then…else'.

C
Comparison operators比較運算符

== equal, != not equal, > greater, < less, >= and <=.

L
Loop循環

Repeating a block of code; Scratch says 'repeat N'.

f
for / range計數循環

for i in range(5) in Python runs 5 times (i counts 0 to 4).

I
Indentation縮排

Python uses leading spaces to show which lines belong inside an if or loop; no indent, no work.

w
while loopwhile 循環

A loop that repeats while a condition stays true; the condition must be able to turn false or the loop never ends.

M
Modulo (%)求餘數運算符(%)

The operator giving a division's remainder, e.g. 7 % 2 = 1; remainder 0 means even.

3Step by step Steps

  1. 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.
  2. 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'.
  3. 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.
  4. 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.
  5. 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.
  6. 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

條件與循環:程式嘅思考與重複 if & loops條件 if:揀路行if 分數 ≥ 50:顯示「合格」else:顯示「要加油」電腦幫你做決定循環 loop:重複做for 次數 in range(10):畫一個正方形邊→ 10 次重複,唔使寫 10 次電腦最叻就係重複寫一次,跑無限次組合威力:遊戲入面「每一秒檢查一次(loop)玩家有冇中彈(if)」無限循環要小心:條件永遠成立就停唔到——記得留出口
Fig. 1: If and loops

5Worked example Example

Example: what does this output? for i in range(3): with print(i) indented inside

  1. 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.
  2. The loop feeds each i to print in turn, so print runs three times, printing 0, 1 and 2 on separate lines.
  3. A common error is expecting 1, 2, 3; keep the rule 'starts at 0, end not included' in mind and the trap is avoided.
  4. Extension: to output 1, 2, 3, write range(1, 4) — the start 1 is included, the end 4 is not.
  5. 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

✗ Testing equality with one sign: if x = 5.
✓ Equality needs two signs ==; a single = assigns a value and Python will reject the line.
✗ Thinking range(3) gives 1, 2, 3.
✓ Python counts from 0: range(3) is 0, 1, 2; for 1 to 10 write range(1, 11).
✗ Leaving the line under an if unindented.
✓ Indentation defines what is inside the if or loop; without it you get a SyntaxError or wrong logic.
✗ Writing a while whose condition never turns false.
✓ That becomes an infinite loop that never stops; change something inside so the condition can end.

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

Other subjects in this grade

Same subject, other grades