Worksheets › Class 11 › Flow of Control › Cheat sheet
Class 11 Flow of Control: cheat sheet
CBSE Computer Science. if, elif and else choose what runs; for with range() and while repeat it; break and continue change a loop; nested loops print patterns.
Key ideas
- In an if–elif–else chain only the first true branch runs; else runs when no condition is true.
- range(a, b, c) starts at a, goes in steps of c and stops before b; range(n) gives 0 to n − 1.
- A while loop repeats while its condition is True, so something in its body must change for it to stop.
- break leaves the loop at once; continue skips the rest of this pass and starts the next one.
- In nested loops the inner loop runs right through on every pass of the outer loop.
- Indentation (usually 4 spaces) shows which lines belong to an if, an else or a loop.
- Number programs use % 10 for the last digit and // 10 to drop it; Fibonacci uses a, b = b, a + b.
Remember
| range() | list(range(5)) = [0, 1, 2, 3, 4]; list(range(1, 10, 3)) = [1, 4, 7] |
| Adding 1 to n | sum of range(1, n + 1) = n(n + 1)/2: 1 to 10 gives 55 |
| Nested loops | range(3) inside range(4): the inner body runs 12 times |
| Special numbers | Armstrong: 153 = 1³ + 5³ + 3³; perfect: 28 = 1 + 2 + 4 + 7 + 14 |
| break | for i in range(1, 30): if i * i > 50: break print(i) # 8 |
| continue | for i in range(1, 8): if i % 3 == 0: continue print(i, end=' ') # 1 2 4 5 7 |
Watch out
- Including the stop value: range(1, 10) ends at 9.
- Expecting two branches of an if–elif chain to run.
- Forgetting to change the variable a while loop tests, so it never ends.
- Mixing up break (leave the loop) with continue (go on to the next pass).
Worked example
What are a, b and c after these lines run? a, b, c = 72, 52, 86 if a > b: a, b = b, a if b > c: b, c = c, b if a > b: a, b = b, a
Working: each swap puts the smaller value first: the three numbers end up sorted
Answer: a = 52, b = 72, c = 86
Practise Flow of Control
Revise with this page, then practise: every Flow of Control sheet in the app is new, with an answer key and working.
Coming soon for Android and iPhone.