TechTayari

S10 · Computer Studies I · Grade 10 · ages 15–16

Decisions & Loops

Control structures in Python

Grade 10 · 3.4 Control StructuresCBE strandFree · works offline

▶ Start the interactive lesson

The full lesson adds narration, an interactive mission and a 10-question bank, and the quiz explains any mistakes.

Three control structures

Every program is built from three structures. Sequence: steps run one after another. Selection: the program chooses a path with if. Iteration: the program repeats steps with a loop. Combine these and you can solve almost any problem.

Selection with if, elif and else

if checks a condition; elif ("else if") checks another; else runs when none matched. For example: if marks >= 80, print "A"; elif marks >= 50, print "Pass"; else print "Try again". Python uses a colon and indentation (usually 4 spaces) to show which lines belong to each branch.

for loops

A for loop repeats once for each item. range(5) gives 0, 1, 2, 3, 4 (five numbers, starting at 0). range(1, 6) gives 1 to 5. Example: for i in range(3): print(i) prints 0, then 1, then 2.

while loops

A while loop repeats as long as a condition is True, which suits cases where you don't know how many repeats are needed, like asking for a PIN until it is correct. Make sure something inside the loop changes the condition, or it will loop forever.

break and continue

break leaves a loop immediately, for example when you find what you were searching for. continue skips the rest of this round and jumps to the next one, for example to skip negative numbers. Use them sparingly, to keep loops easy to follow.

Key points

  • Programs use three structures: sequence, selection and iteration.
  • if, elif and else choose which path the program takes.
  • Python uses a colon and indentation to show what belongs to each part.
  • A for loop repeats once for each item, and range starts counting at zero.
  • A while loop repeats as long as a condition stays true.
  • Make sure a while loop's condition eventually becomes false.
  • break leaves a loop; continue skips to the next round.

Try it for real: Program a grader

  • Write a program that inputs a mark and prints A for 80 and above, Pass for 50 to 79, and Try again below 50.
  • Write a loop that prints the 7 times table from 7 × 1 to 7 × 12.
▶ Start the interactive lesson