Skip to content

← Grade 8

Decisions and Loops in Python

Unit 2 · Algorithms and programming

Hide the stories, facts, photos, activities and interactives, for revising before an exam
In this unit 11 sections
  1. Choosing with if
  2. More than two paths: elif
  3. Repeating with for
  4. Drawing with loops
  5. Counting and adding up
  6. Repeating with while
  7. Loops that never end
  8. Reading a program: what each part is for
  9. Plan, then type
  10. In short
  11. Exercise

Open a mobile wallet and send Rs 500 to a friend. Before the money moves, the app checks: is there enough in your account? If there is, it sends; if not, it says so. When it shows your last fifty payments, it does the same few steps fifty times, once for each payment. Every app on your phone is full of these two things: choosing what to do, and repeating steps.

In Grade 6 your turtle repeated, and in Grade 7 your block programs chose with if and else. In Unit 1 you read an if in Python. In this unit you write programs that choose between two, three or eight paths, that repeat a set number of times or until a job is done, that count and add up as they go, and that draw with the turtle again, now in Python. You will also learn to read any short program and say what each part of it is for, and to find the loop that never ends.

Choosing with if

In Unit 1’s shop project the change came out as a minus number when a customer gave too little. Now the program can check first:

total = 180given = int(input("Money given: Rs "))if given < total:    print("That is not enough.")    print("Please give Rs", total - given, "more.")print("Thank you!")

Output

Money given: Rs 150That is not enough.Please give Rs 30 more.Thank you!

Run it twice: once with 150, and once with 200. With 200, lines 4 and 5 are skipped, and the program only says Thank you!

An if statement has three parts:

  • the word if, then a condition, as in Grade 7: anything that works out to True or False, such as given < total;
  • a colon : at the end of the line;
  • the lines inside it, each indented by four spaces. Together they are called the if’s block. They run only when the condition is True.

The first line that goes back to the left edge, line 6 here, is outside the if: it runs whichever way the condition came out. In Grade 7 a block sat in the if’s mouth; in Python it sits under the if, four spaces in.

If and else

With else, exactly one of two blocks runs, as it did in Grade 7. In Unit 1’s Exercise you shared students out into 40-seat buses. Now the program can say whether an extra bus is needed:

students = int(input("How many students? "))full_buses = students // 40last_bus = students % 40if last_bus == 0:    print(full_buses, "full buses, and no other bus.")else:    print(full_buses, "full buses, and one more bus with", last_bus, "students.")

Output

How many students? 1303 full buses, and one more bus with 10 students.

Try it with 120 too. else: has no condition of its own: it means “in every other case”. It sits level with its if, and its block is indented under it.

Joining conditions

Grade 7’s and, or and not join conditions in an if, just as they did in blocks. A school trip is for Grades 6 to 8:

grade = int(input("Which grade are you in? "))if grade >= 6 and grade <= 8:    print("You can come on the trip!")else:    print("Sorry, this trip is for Grades 6 to 8.")

Output

Which grade are you in? 9Sorry, this trip is for Grades 6 to 8.

Each side of and must be a whole condition: grade >= 6 and <= 8 is a SyntaxError.

money holds 100. What does this print?

if money >= 100:    print("Buy the book.")print("Go home.")

Pick an answer to see why.

Which condition is True only for ages 13 to 19?

Pick an answer to see why.

More than two paths: elif

In Grade 7 the bus fare had a second rule added: children under 5 ride free, students aged 5 to 18 pay half, Rs 15, and everyone else Rs 30 (made-up prices). You did it with an if/else inside another if/else. Python can do that too, but it has a neater way: elif, short for “else if”.

Try it

Three fares, two ways

Tap the outer else block, then the if inside it. Both become one line of Python. Then run the Python as a 3-year-old, a 13-year-old and a 30-year-old.

Blocks

ask becomes input(), with int( ) round it, because the age is compared with numbers.

Python

age = int(input("How old are you? "))if age < 5:    fare = 0elif age < 19:    fare = 15else:    fare = 30print("Your fare is Rs", fare)

Python asks the conditions in order, from the top. The first one that is True wins: its block runs, and every condition below it is skipped, without even being asked. If none is true, the else block runs. So exactly one of the three fares is set.

ask ageage < 5 ?age < 19 ?truetruefalsefalseifelifelsefare = 0fare = 15fare = 30print farethe program takesonly one of the three ask ageage < 5 ?age < 19 ?truetruefalsefalseifelifelsefare = 0fare = 15fare = 30the program takesonly one of the threeprint fare
Figure 2.1 The bus fare with if, elif and else, as paths. The questions are asked from the top down; the first that is true decides. A 13-year-old goes false at the first question, true at the second, and pays Rs 15; the else path, fare = 30, is never taken.

An if can have as many elif parts as it needs, and the else at the end is allowed to be left out (then, if no condition is true, nothing in the if runs).

A grade calculator

Nepal’s school exams give each subject a letter grade. As of 2026, the grades of the SEE (the exam at the end of Grade 10) are:

Marks (%) Grade
90 and above A+
80 to under 90 A
70 to under 80 B+
60 to under 70 B
50 to under 60 C+
40 to under 50 C
35 to under 40 D
below 35 NG

NG means “not graded”. Here is the table as a program. Each elif only needs to check the bottom of its band, because anyone above the top of it was caught by a line above.

marks = int(input("Marks out of 100: "))if marks >= 90:    grade = "A+"elif marks >= 80:    grade = "A"elif marks >= 70:    grade = "B+"elif marks >= 60:    grade = "B"elif marks >= 50:    grade = "C+"elif marks >= 40:    grade = "C"elif marks >= 35:    grade = "D"else:    grade = "NG"print("Your grade:", grade)

Output

Marks out of 100: 85Your grade: A

Try it

Step through the grades

Press Next line again and again, and watch which conditions Python asks. Then choose another student’s marks. How many conditions are asked for 85? For 30?

marks = int(input("Marks out of 100: "))if marks >= 90:    grade = "A+"elif marks >= 80:    grade = "A"elif marks >= 70:    grade = "B+"elif marks >= 60:    grade = "B"elif marks >= 50:    grade = "C+"elif marks >= 40:    grade = "C"elif marks >= 35:    grade = "D"else:    grade = "NG"print("Your grade:", grade)
Step 1 / 5
The user types:

The user types 85, and int() turns it into a number.

Variables

marksgrade
85–

Output

Marks out of 100: 85 
Answer

temp = 18. What does this print?

if temp > 30:    print("Hot")elif temp > 15:    print("Warm")elif temp > 5:    print("Cool")else:    print("Cold")

Pick an answer to see why.

In an if with two elifs and an else, how many of the four blocks can run?

Pick an answer to see why.

Repeating with for

In Grade 6 the turtle drew a square with repeat 4 times. Here is that program next to the same program in Python:

Try it

The square, two ways

Tap each block to see its Python. Then press Run under the Python: the turtle draws its square under the program.

Blocks

repeat 4 times becomes for i in range(4):, with a colon. i counts the rounds: 0, 1, 2, 3.

Python

import turtlet = turtle.Turtle()for i in range(4):    t.forward(100)    t.right(90)

for i in range(4): is Python’s repeat 4 times. The lines indented under it are the loop’s body, the blocks in its mouth. A for loop runs its body once for each number that range() gives. Repeating steps like this is called iteration (Grade 7 called it repetition: the same idea), and each time round the loop is one iteration.

The loop variable

i is a variable, the loop variable. Each time round, Python puts the next number from range() into it. Print it and you can see:

for i in range(5):    print("Round", i)print("Finished")

Output

Round 0Round 1Round 2Round 3Round 4Finished

range(5) gives five numbers, but they start at 0, and so they end at 4, not 5. Python, like most programming languages, counts from 0. The print("Finished") is back at the left edge: it runs once, after the loop.

range() can be told where to start, and how big a step to take:

You write The numbers How many
range(5) 0, 1, 2, 3, 4 5
range(1, 6) 1, 2, 3, 4, 5 5
range(2, 11, 2) 2, 4, 6, 8, 10 5
range(10, 0, -1) 10, 9, 8, … 1 10

The rule is always the same: start at the first number, move by the step (1 if you don’t give one), and stop before the stop number. The stop number itself is never given. So range(1, 11) gives 1 to 10, and a loop over range(a, b) runs b − a times.

Try it

The numbers range() gives

Move the sliders and watch which numbers range() gives. Can you make it give 1 to 10? The even numbers up to 14? A countdown from 10 to 1? What happens when the step is 0?

12345678910start 1stop 11
Python
for i in range(1, 11):
The loop runs
10 times

It starts at 1 and goes up by 1 each time. It stops before 11: the stop number itself is never given.

Answer

A times table

Once you have the loop variable, a times table is two lines:

n = int(input("Which times table? "))for i in range(1, 11):    print(n, "×", i, "=", n * i)

Output

Which times table? 77 × 1 = 77 × 2 = 147 × 3 = 217 × 4 = 287 × 5 = 357 × 6 = 427 × 7 = 497 × 8 = 567 × 9 = 637 × 10 = 70

The × inside the quotes is only text to print; Python’s own multiply is the * in n * i. Each time round, i is one more, and n * i is worked out afresh.

How many times does for i in range(3, 10): run its body?

Pick an answer to see why.

What is the last number range(0, 20, 5) gives?

Pick an answer to see why.

Drawing with loops

Python’s turtle is Grade 6’s turtle: it starts in the middle facing right, with its pen down. Its commands are words:

Block (Grade 6) Python
move 100 steps t.forward(100)
turn right 90 degrees t.right(90)
turn left 90 degrees t.left(90)
pen up, pen down t.penup(), t.pendown()
(a color for the pen) t.color("red")

Every turtle program starts with two lines. import turtle brings Python’s turtle module (a set of ready-made tools) into the program, and t = turtle.Turtle() makes a turtle and keeps it in the variable t. The t. in front of each command says which turtle is to do it. A program may end with turtle.done(): on a computer it keeps the turtle’s window open until you close it; here on the page it does nothing.

Any regular shape

In Grade 6 you found that a turtle going once round a shape turns 360° in all, so each turn of a regular shape is 360° ÷ the number of sides. Now the number of sides can be a variable:

import turtlet = turtle.Turtle()sides = 6for i in range(sides):    t.forward(80)    t.right(360 / sides)turtle.done()

Change sides = 6 to 5, 8 or 20, and run it again. With 20 sides it almost looks like a circle. Change it to sides = int(input("How many sides? ")), and the user chooses.

The loop variable in a drawing

In Grade 7 a variable that grew drew a spiral. In Python, the loop variable can grow for you:

import turtlet = turtle.Turtle()for i in range(1, 41):    t.forward(i * 5)    t.right(90)turtle.done()

Each side is 5 steps longer than the one before: 5, 10, 15, … 200. Try t.right(91), or t.right(120).

Choosing inside a loop

A loop and an if work together. Here the turtle draws a row of squares and colors every other one red. i % 2 == 0 is True when i is even:

import turtlet = turtle.Turtle()t.penup()t.goto(-150, 0)t.pendown()for i in range(6):    if i % 2 == 0:        t.color("red")    else:        t.color("blue")    for side in range(4):        t.forward(40)        t.right(90)    t.penup()    t.forward(50)    t.pendown()turtle.done()

Look at the indents: the if, the inner for and the pen moves are all inside the outer loop, so each happens six times; the lines inside the inner for happen 4 × 6 = 24 times. A loop inside a loop is a nested loop, as in Grade 6. t.goto(-150, 0) moves the turtle straight to a point: 150 steps left of the middle (with the pen up, so it leaves no line).

In the loop below, how many lines does the turtle draw?

for i in range(3):    for j in range(5):        t.forward(50)        t.right(72)

Pick an answer to see why.

Counting and adding up

Loops do much more than draw. Two small patterns, used in almost every program, turn a loop into a counter and a calculator.

Adding up

Add the numbers from 1 to 5. A person adds them one at a time, keeping the sum so far in their head: 1, then 1 + 2 = 3, then 3 + 3 = 6… A program does the same, with a variable for the sum so far:

total = 0for n in range(1, 6):    total = total + nprint("Total:", total)

Output

Total: 15

Try it

Watch the total grow

Step through it. Watch the two variables: n takes the next number each time round, and total grows by n.

total = 0for n in range(1, 6):    total = total + nprint("Total:", total)
Step 1 / 13

The running total starts at 0, before the loop.

Variables

ntotal
–0

Output

 

total is a running total: a variable that starts at 0 before the loop, has each new value added to it inside the loop, and holds the answer after the loop. The three places matter:

  1. Before the loop: total = 0. Not inside it, or it would go back to 0 every time round.
  2. Inside the loop: total = total + n, once for each value.
  3. After the loop, back at the left edge: use the total. Inside the loop, it would be printed after every number.

Change range(1, 6) to range(1, 101) and run it: the numbers from 1 to 100 add up to 5,050, in less time than it takes to blink.

Counting

A counter is a variable that counts how many times something happens. It also starts at 0, and goes up by 1 each time, usually inside an if. How many numbers from 1 to 100 can be divided exactly by 7?

count = 0for n in range(1, 101):    if n % 7 == 0:        count = count + 1print(count, "numbers from 1 to 100 divide exactly by 7.")

Output

14 numbers from 1 to 100 divide exactly by 7.

Adding up what the user types

In Grade 7’s guessing game, one ask block inside a loop asked again every round. Python works the same way: one input() inside a loop asks as many times as the loop goes round. Here a student types the marks of five subjects:

total = 0for i in range(5):    marks = int(input("Marks: "))    total = total + marksprint("Total:", total)print("Average:", total / 5)

Output

Marks: 72Marks: 65Marks: 80Marks: 58Marks: 90Total: 365Average: 73.0

On this page, each answer you type runs the program again from the top with your answers so far (Unit 1), so with five questions you may see the output flicker five times. The answers are kept, and the program ends as on a computer.

A program must count how many students in a class passed. Where does passed = passed + 1 go?

Pick an answer to see why.

What does this print?

total = 0for n in range(1, 4):    total = total + n * 2print(total)

Pick an answer to see why.

Repeating with while

A for loop is for when you know how many times to go round: 4 sides, 10 lines of a table, 5 subjects. Often you don’t. Pema saves Rs 150 a week for a football that costs Rs 1,000. How many weeks will it take? In Grade 6 this was repeat until: repeat until the savings reach Rs 1,000. Python has a while loop: repeat while a condition is True.

saved = 0weeks = 0while saved < 1000:    saved = saved + 150    weeks = weeks + 1print("Weeks:", weeks)print("Saved: Rs", saved)

Output

Weeks: 7Saved: Rs 1050

A while loop works like this:

  1. Check the condition. If it is False, the loop is over: go to the first line after it.
  2. If it is True, run the body, then go back to step 1.

So the condition is checked before every round, including the first. If it is False from the start, the body never runs at all.

Try it

Step through the savings

Watch line 3: Python comes back to it after every round, and asks again. After which week is saved < 1000 first False?

saved = 0weeks = 0while saved < 1000:    saved = saved + 150    weeks = weeks + 1print("Weeks:", weeks)print("Saved: Rs", saved)
Step 1 / 26

Pema has saved nothing yet.

Variables

savedweeks
0–

Output

  
Answer

Asking again

A while loop is just right for asking again until the answer makes sense. Marks must be from 0 to 100:

marks = int(input("Marks out of 100: "))while marks < 0 or marks > 100:    print("Marks must be from 0 to 100. Try again.")    marks = int(input("Marks out of 100: "))print("Thank you. You typed", marks)

Output

Marks out of 100: 150Marks must be from 0 to 100. Try again.Marks out of 100: 85Thank you. You typed 85

Nobody knows in advance how many tries the user will need, so a for loop can’t do this. With a good answer the first time, the condition is False at once, and the body never runs.

for or while?

Use When Example
for you know how many times before the loop starts the 10 lines of a times table; the 7 days of a week
while you go round until something happens, and don’t know how many times that takes saving until there is enough; asking until the answer makes sense

Any for loop can be written as a while loop with a counter, but the for is shorter and can’t forget to count.

How many times does this print Namaste?

n = 10while n < 5:    print("Namaste")    n = n + 1

Pick an answer to see why.

Which loop fits best: “keep filling bottles from the tank until the tank is empty”?

Pick an answer to see why.

Loops that never end

A while loop stops only when its condition becomes False. If nothing inside the loop ever makes it False, the loop goes round forever. This is an infinite loop, and it is one of the most common bugs. Here is a countdown with a mistake:

n = 10while n > 0:    print(n)    n = n + 1print("Go!")

Try it

A countdown that never ends

Step through it and watch n. Will n > 0 ever be False?

n = 10while n > 0:    print(n)    n = n + 1print("Go!")
Step 1 / 25…

The countdown starts at 10.

Variables

n
10

Output

        
Answer

If you press Run under the countdown, the page shows numbers pouring down, then stops the program with a message: it printed far too much. A loop that prints nothing is stopped after 10 seconds instead. While a program runs, its Run button says Stop: press it to stop the program yourself. On a computer, press Ctrl and C together to stop a program that won’t end (Python stops with KeyboardInterrupt).

Finding an infinite loop

An infinite loop has no error message: the program just never finishes, or prints forever. Look at the while loop’s condition and ask three questions:

  1. Does anything in the body change the condition? while count < 5: with no line changing count is stuck. A line that changes it, but sits outside the loop because it isn’t indented, doesn’t count.
  2. Does it change it the right way? Adding when it should take away moves away from the end, as in the countdown.
  3. Can the condition ever be reached? while n != 10: with n going 0, 3, 6, 9, 12… jumps over 10 and never stops. while n < 10: would.

Why does this loop never end?

x = 1while x < 100:    x = x * 1

Pick an answer to see why.

Reading a program: what each part is for

Programmers spend more time reading programs than writing them: their own from last month, a friend’s, or one from a book. To understand a program, ask what each part is for. Nearly every program is made of the parts you have now met:

  • Sequence: lines run one after another, from the top.
  • Selection: an if, elif or else chooses which lines run.
  • Iteration: a for or while loop runs lines again and again.
  • Procedures (in Python, functions): named sets of steps that a line calls to do a job, such as print(), input(), range() and t.forward(). These come ready-made; in Unit 4 you will write your own.
  • Variables, each with a job, its role. The same few roles turn up again and again:
Role What it does Example
loop variable takes the next value each time round a for loop i in for i in range(5):
counter starts at 0 and goes up by 1 each time something happens passed = passed + 1
running total starts at 0, and each new value is added to it total = total + marks
highest so far changes only when a bigger value comes along if marks > highest: highest = marks
input value holds the latest thing the user typed marks = int(input("Marks: "))
flag True or False: has something happened yet? found in Grade 7’s guessing game, a true/false variable

Try it

What is this line for?

Each card is a line from a program you have seen in this unit. What is its job?

for day in range(1, 8):

What is this line for in its program?

Tap a group above.

Card
1 of 12
Right the first time
0

Here is a program for a teacher with three students. Read it, then step through it.

passed = 0total = 0for i in range(3):    marks = int(input("Marks: "))    total = total + marks    if marks >= 35:        passed = passed + 1print("Passed:", passed)print("Average:", total / 3)

Try it

Trace it for two classes

Before you press Next line, say what each line is for. Then step through it for the first class, and write its trace table. Then choose the second class, and predict what it will print before you step.

passed = 0total = 0for i in range(3):    marks = int(input("Marks: "))    total = total + marks    if marks >= 35:        passed = passed + 1print("Passed:", passed)print("Average:", total / 3)
Step 1 / 19
The user types:

passed is a counter: it starts at 0.

Variables

imarkstotalpassed
–––0

Output

     
Answer
Edsger Dijkstra, an older man with glasses, a gray beard and a red sweater vest
Figure 2.2 Edsger Dijkstra (1930–2002) in 2002. From 1984 to 1999 he taught at the University of Texas at Austin, in the United States. He also invented a way of finding the shortest route between two places on a map, which every computer science student still learns. Photo: Hamilton Richards, CC BY-SA 3.0

Try it

Errors in loops and ifs

Four short programs, each with one mistake. Read the message, tap the line, name the error, choose the fix.

What Python says

  File "main.py", line 2
    if marks = 40:
       ^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

1. Which line does the message name? Tap it in the program.

Read the message from the bottom up: the last line says what went wrong, the line above it where.

Program 1 of 4 · right the first time: 0 of 12

In for day in range(1, 8):, what role does day have?

Pick an answer to see why.

Plan, then type

A program with loops and ifs needs more planning than one without. As well as Unit 1’s steps (say what it does, list the variables, write the steps in plain words, type a little and run it), ask:

  1. What repeats? That is the body of a loop. Do you know how many times (for), or until what (while)?
  2. What is chosen? Each choice is an if. Are the choices separate questions (separate ifs), or one question with several answers (if, elif, else)?
  3. What must be remembered from round to round? A counter, a total, the highest so far? Set each before the loop.
  4. Test the edges: the marks on each side of a grade’s boundary; a loop that should run 0 times; the last round.

In short

Exercise

What does this print?

x = 7if x > 5:    print("A")elif x > 3:    print("B")else:    print("C")

Pick an answer to see why.

How many times does for i in range(2, 12, 3): go round?

Pick an answer to see why.

Which line starts a loop that runs exactly 10 times?

Pick an answer to see why.

A while loop’s condition is False the first time it is checked. What happens?

Pick an answer to see why.

What is the value of total after this program?

total = 0for n in range(4):    total = total + n

Pick an answer to see why.

In a program, found = False is set before a loop and found = True inside an if in the loop. What is found’s role?

Pick an answer to see why.

a.

What is the difference between if … elif … else and several separate ifs? Give an example where they print different things.

Answer
b.

Write the numbers each of these gives: i. range(6) ii. range(3, 8) iii. range(1, 10, 3) iv. range(5, 0, -1) v. range(4, 4)

Answer
c.

Write the output of this program.

for i in range(1, 4):    print(i, i * i)print("Done")
Answer
d.

Make a trace table for this program, and give its output.

a = 1b = 0while a < 20:    b = b + 1    a = a * 3print(a, b)
Answer
e.

Write a program that prints the 5 times table from 5 × 1 to 5 × 12, then the total of all twelve answers.

Answer
f.

Write a Python program that makes the turtle draw an equilateral triangle with sides of 100 steps, using a loop. Then say what you would change to draw a regular pentagon.

Answer
g.

A student wrote this to say whether a temperature is hot (over 30 °C), warm (16 to 30) or cold (15 and below). It says Warm for 35 °C. Explain the mistake and correct it.

temp = 35if temp > 15:    print("Warm")elif temp > 30:    print("Hot")else:    print("Cold")
Answer
h.

This program should print the even numbers from 2 to 10, but it never stops. Why? Correct it in two different ways.

n = 2while n != 11:    print(n)    n = n + 2
Answer
i.

Explain the role of each variable, each loop and each if in this program, and say what it prints when the user types 4, 7 and then 0.

count = 0total = 0number = int(input("A number (0 to stop): "))while number != 0:    count = count + 1    total = total + number    number = int(input("A number (0 to stop): "))print(count, "numbers, adding up to", total)
Answer
j.

A shopkeeper has 50 kg of rice and sells 7 kg a day. Write a program with a while loop that works out how many full days the rice lasts, and how much is left. Then say how you could get the same answers without a loop, using Unit 1’s operators.

Answer