Worksheets › Class 9 › Conditions and Loops › Cheat sheet
Class 9 Conditions and Loops: cheat sheet
CBSE Computational Thinking and AI. if, elif and else choose which lines run; for and while loops repeat them. Indentation shows which lines belong to each block.
Key ideas
- if checks a condition; elif is checked only if every condition above it was False; else runs when none was True.
- In an if–elif chain, only the FIRST true branch runs, even if later ones are also true.
- The lines inside an if or a loop are indented (usually 4 spaces); wrong indentation changes the program.
- range(a, b, c) starts at a, goes up in steps of c, and stops BEFORE b; range(n) gives 0 to n − 1.
- A while loop repeats as long as its condition is True; something inside must change so that it can stop.
- In nested loops the inner loop runs completely on every turn of the outer loop.
Remember
| range(5) | 0, 1, 2, 3, 4 (five values) |
| range(1, 10, 3) | 1, 4, 7 |
| Sum 1 to n | range(1, n + 1), with s starting at 0 |
| Nested loops | range(3) inside range(4): 12 runs |
| A grade chain | if marks >= 90: print('A') elif marks >= 75: print('B') else: print('C') |
| A while loop | n = 20 while n > 5: n = n - 6 print(n) # 2 |
Watch out
- Thinking range(1, 10) includes 10: it stops at 9.
- Expecting more than one branch of an if–elif chain to run.
- Putting print inside the loop (indented) when it should run once after it.
Worked example
This program should print the first 7 even numbers starting from 2. for i in range(2, 14, 2): print(i) (a) Write the numbers it actually prints. (b) How many numbers is that? (c) What is the smallest stop value for range that prints all 7 numbers?
Working: range stops before its stop value, so it must be more than 14
Answer: (a) 2, 4, 6, 8, 10, 12; (b) 6; (c) 15
Practise Conditions and Loops
Revise with this page, then practise: every Conditions and Loops sheet in the app is new, with an answer key and working.
Coming soon for Android and iPhone.