Skip to content

← Algorithms and programming

Programming: Variables and Choices

Unit 3 · Algorithms and programming

Hide the stories, facts, photos, activities and interactives, for revising before an exam
In this unit 12 sections
  1. Variables in a program
  2. Three types of value
  3. Input: asking a question
  4. Conditions: true or false
  5. If and if/else
  6. Tracing a program
  7. Build a quiz game
  8. A scoring game: guess my number
  9. A variable that grows
  10. Plan, then build
  11. In short
  12. Exercise

Play a game on a phone and watch what it keeps track of: your score, your lives, your name on the high-score list, the level you have reached. Then watch what it decides. Did you answer right? Then add a point. Did you run out of lives? Then the game is over. A game without memory or choices would be no game at all: it would do the same thing every time, whatever you did.

In Grade 6 you planned algorithms that remember things in variables and make choices, and you made a turtle draw with blocks. In this unit you put the two together. You will write programs that ask you questions, remember your answers, check them, and decide what to do next. By the end you will have built a quiz game that keeps your score and a number-guessing game, and you will be able to follow any short program by hand and say what it does.

Variables in a program

A cricket scorer keeps one number in mind all through an innings: the runs. It starts at 0. A four makes it 4; a six on the next ball makes it 10. The scorer never writes a new page for every ball. There is one place for the runs, and its number changes.

A program does the same with a variable: a named place in the computer’s memory that holds one value. The program can look at the value, and can put a new value in. As in Grade 6, think of a box with a name on its lid.

In our blocks, two blocks put values into a variable:

  • set runs to 0 puts 0 into the variable runs. Whatever was in it before is gone.
  • change runs by 4 adds 4 to the number already in runs. If runs held 6, it now holds 10. To take away, change by a minus number: change runs by -1.

To use the value inside a variable, drag the variable’s own round block (runs) into a slot of another block. Wherever that block runs, the computer looks in the box and uses whatever value is in it at that moment.

Try it

A cricket scorer

Press Step to run the program one block at a time. After each block, look at the runs box and at the new row of the trace table under it. Then press Run to see it all at once. Change the numbers, or add a change runs by 6 block, and run it again.

What the program says and asks appears here.

runs – no value
StepBlockruns

Press Run to start the program, or Step to do one block at a time.

Loading the blocks…

The say block shows something in the output box, the way a phone app shows a message. join puts two pieces together, one after the other: join “Runs: ” runs makes the words Runs: followed by whatever number is in runs, such as Runs: 11. The space after the colon is inside the quotes, so it is part of the text.

Good names

You can name a variable almost anything, but choose names that say what is inside: runs, score, price, name. A program with variables called a, b and x2 works just as well for the computer, but a person reading it, including you a week later, can’t tell what each one is for. To make a new variable, press Make a variable at the start of the blocks and type its name.

A program runs set score to 5, then change score by 3, then set score to 0, then change score by 2. What is in score at the end?

Pick an answer to see why.

Why should a variable be called cups rather than c?

Pick an answer to see why.

Three types of value

In Grade 6 you met three data types: numbers, text, and yes/no. A program uses the same three. The yes/no type is written true or false in a program, and it gets its own name, Boolean (after George Boole, an English mathematician of the 1800s). Each type is good for different jobs:

Type Examples What you can do with it
number 12, 0, 7.5, −30 add, take away, multiply, divide; ask which is bigger
text “Sita”, “Bhaktapur”, “Runs: ” join it to other text; check whether it is the same as other text
true/false (Boolean) true, false decide what to do next: if it is true, do this

Text is usually called a string by programmers (a string of letters), and you will see that word in Grade 8.

In our blocks, what you type into a slot is kept as a number if it looks like a number, and as text if it doesn’t: type 12 and you get the number 12, type Sita and you get the text “Sita”. True and false have a block of their own. The boxes over the editor show each variable’s type beside its value.

Try it

Three types

Run the program and look at the three boxes: name holds text, age a number, student true/false. Then try to break it: change set age to 12 to set age to twelve (the word) and run it again. What does the computer say, and why?

What the program says and asks appears here.

name – no value
age – no value
student – no value

Press Run to start the program, or Step to do one block at a time.

Loading the blocks…

Answer

What happens when you put a number and text together depends on the block. 12 + 1 is 13, because + works on numbers. join 12 1 is 121, because join works on text: it puts the 1 after the 12, side by side, as you would write them on paper.

What does join 10 5 make?

Pick an answer to see why.

A program keeps whether a student has paid their exam fee. Which type of variable suits it best?

Pick an answer to see why.

Input: asking a question

The cricket program always does the same thing: the runs are written into its blocks. Most useful programs work with input, information that comes in from outside while the program runs: a number you type, a button you tap, a photo you choose. A mobile wallet asks how much you want to send; a bus-ticket app asks where you are going. The program can’t know the answer in advance, so it keeps it in a variable and uses it from there.

Our input block is ask … and keep the answer in …. It shows the question, waits until you type an answer and press OK, then puts what you typed into the variable you chose. Then the program carries on.

Here is the tea shop’s bill from Grade 6, now as a real program, for milk tea only. (The price, Rs 30 a cup, is the same made-up one.)

Try it

The tea shop’s bill

Run it and answer the two questions. Then run it again as a different customer. The blocks don’t change; only what goes into the variables does.

What the program says and asks appears here.

name – no value
cups – no value
bill – no value
StepBlocknamecupsbill

Press Run to start the program, or Step to do one block at a time.

Loading the blocks…

set bill to cups × 30 works out the bill from whatever cups holds, and keeps the answer in bill. A block that works something out like this, from values and variables, is called an expression.

What you type arrives as characters: as you saw in Unit 2, the digit 2 is stored as its character code, 50. Our blocks change an answer that looks like a number into a real number before using it, so 2 cups can be multiplied by 30. But if a customer types a word where the program needs a number, such as two instead of 2, the program stops with a message: the text “two” can’t be multiplied by 30. The type of a value matters even when it comes from input.

What is the input in the tea shop program?

Pick an answer to see why.

Conditions: true or false

Before a program can choose, it needs a question with only two answers. A question like that is called a condition, as in Grade 6: it is either true or false. In a program, conditions are usually comparisons:

Condition Read it as When age is 12
age < 13 age is less than 13 true
age > 12 age is more than 12 false
age = 12 age is equal to 12 true
name = “Sita” name is the same as “Sita” depends on name

The three signs, <** (less than), **> (more than) and = (equal to), are called comparison operators. The pointed end of < and > points at the smaller number: in 5 < 9, the 5 is at the point.

<** and **> compare two numbers. If age holds the text “four”, nobody can say whether it is less than 13, so our blocks stop with a message instead of guessing.

A condition is itself a value, of the true/false type, so you can keep it in a variable. set child to age < 13 works out whether age is less than 13 and keeps true or false in child.

Try it

True or false?

Run it and read child and teenager. Change the age to 13 and run it again, then 5, then 20. Before each run, say what the two variables will hold.

What the program says and asks appears here.

age – no value
child – no value
teenager – no value

Press Run to start the program, or Step to do one block at a time.

Loading the blocks…

What you should see

At the edge

Rules in real life often say “5 or more” or “up to 12”. Our blocks have only <, > and =, as some block languages do. For whole numbers that is enough:

  • “5 or more” is the same as > 4: 5, 6, 7… are all more than 4.
  • “12 or less” is the same as < 13.

The edge is where most mistakes hide. > 5 leaves out 5 itself. This is the bug you found in Grade 6, in the tea shop’s “5 cups or more”.

marks holds 40. Which condition is true?

Pick an answer to see why.

A bus gives a free ride to children under 5. Which condition is true exactly for the children who ride free?

Pick an answer to see why.

If and if/else

Now the program can choose. The if block has a slot for a condition and a mouth for blocks:

  • if condition then …: the blocks in its mouth run only when the condition is true. When it is false they are skipped, and the program goes on below.
  • if condition then … else …: two mouths. When the condition is true, the first runs; when it is false, the blocks under else run instead. Exactly one of the two runs, never both and never neither.

Choosing which blocks to run like this is called selection (in Grade 6 you called it a choice). With sequence and repetition, it is one of the three ways every program is built.

Here is a bus fare: children under 5 ride free, everyone else pays Rs 30 (made-up prices).

ask ageage < 5 ?true or falsetruefalseset fare to 0set fare to 30say farethe program takesonly one of these ask ageage < 5 ?true or falsetruefalseset fare to 0set fare to 30the program takesonly one of thesesay fare
Figure 3.1 The bus fare program as two paths. The condition is checked once. If it is true, the program goes along the path marked true; if false, along the path marked false. Both paths meet again at say fare.

Try it

The bus fare

Run it three times: as a 3-year-old, a 13-year-old and a 4-year-old. Watch which set fare block lights up. Then add a rule: students aged 5 to 18 pay half, Rs 15.

What the program says and asks appears here.

age – no value
fare – no value
StepBlockagefare

Press Run to start the program, or Step to do one block at a time.

Loading the blocks…

Hint
Answer

An if/else inside another if/else, as in the answer above, is called a nested choice, like the nested loops of Grade 6. Each question is asked only when the one before it has sent the program that way.

A program says: if score > 7 then say “Gold” else say “Keep trying”. score holds 7. What does it say?

Pick an answer to see why.

Find the bug

A school lets students pass with 40 marks or more. Here is a program for it. Does it work?

Try it

Passing marks

Run the program with a few marks of your own. Then press Test: the computer runs it for four students and compares what it says with what it should say. Find the bug and fix it, then test again.

What the program says and asks appears here.

marks – no value
TestShould sayIt said
75 marksYou passed.
12 marksNot this time. Try again.
40 marksYou passed.
39 marksNot this time. Try again.

Press Run to start the program, or Step to do one block at a time.

Loading the blocks…

Hint
Answer

Tracing a program

A program with variables and choices can do something different every time, depending on its input. To be sure what it does, you trace it, as in Grade 6: follow it one block at a time, exactly as the computer would, and write the value of each variable after each step in a trace table.

Here is a program. A bus ticket costs Rs 30, and you have Rs 100. How many tickets can you buy?

set tickets to 0set money to 100repeat 4 times    if money > 29 then        change tickets by 1        change money by -30say join “Tickets: ” tickets

Try it

Step through it

Press Step again and again, and check each row of your trace table against the computer’s. Then change the money to 150 and trace it on paper first: how many tickets now, and why?

What the program says and asks appears here.

tickets – no value
money – no value
StepBlockticketsmoney

Press Run to start the program, or Step to do one block at a time.

Loading the blocks…

Answer
A large printed table with many rows and columns of symbols and numbers, headed with the names of variables
Figure 3.2 Lovelace’s table from Note G (1843): each row is one step of the program; the columns hold the variables V1, V2, V3… and the values in them. Photo: Ada Lovelace, Public domain

In a trace table, what does each column show?

Pick an answer to see why.

Build a quiz game

Now you have everything a quiz needs:

  • a variable score, set to 0 at the start;
  • for each question, an ask that keeps the answer in answer;
  • an if/else that checks the answer: if it is right, say so and change score by 1; otherwise, say the right answer;
  • at the end, say the score.

Try it

A quiz game

Play the quiz. Then make it yours: add a third question about something you study (right-click or long-press a block to duplicate it, then change the words). Make the last line say the score out of 3.

What the program says and asks appears here.

score – no value
answer – no value

Press Run to start the program, or Step to do one block at a time.

Loading the blocks…

Each question is the same few blocks with different words. That is a pattern you will turn into one reusable block in Grade 8, called a function.

Try it

A quiz with a bug

Your friend played this one-question quiz before you, and the score box still shows their 3. Run it and answer right. Run it again and answer right again. What happens to the score? Then fix it.

What the program says and asks appears here.

answer – no value
score 3 number

Press Run to start the program, or Step to do one block at a time.

Loading the blocks…

Answer

Your quiz has 5 questions and starts with set score to 0. A player gets 3 right. Which block ran 3 times?

Pick an answer to see why.

A scoring game: guess my number

In this game the computer thinks of a number from 1 to 20 and you have 5 guesses to find it. After each wrong guess it tells you whether to go bigger or smaller. You start with 5 points and lose one for each wrong guess.

The program uses a new block, random number from 1 to 20, which picks a whole number by chance, a different one each game. Its variables are of two types, numbers and true/false:

Variable Type What it holds
secret number the number the computer picked
guess number your latest guess
points number your points so far
found true/false whether you have found it yet

found starts as false. When you guess right, it is set to true, and from then on the if found = false inside the loop skips the rest of the rounds.

Try it

Guess my number

Play it a few times. What is the best way to guess? Then change the game: make the number go up to 50, give 7 guesses, or start with 10 points.

What the program says and asks appears here.

secret – no value
found – no value
points – no value
guess – no value

Press Run to start the program, or Step to do one block at a time.

Loading the blocks…

What you should see

In the guessing game, why is found a true/false variable and not a number?

Pick an answer to see why.

A variable that grows

Variables work with the turtle too. In this program the length of each line is a variable, side, which grows by 10 every time round the loop. The turtle draws a square spiral.

Try it

A growing spiral

Run it. Then change it: make side grow by 5, or turn 91 degrees instead of 90, or 120.

What the program says and asks appears here.

side – no value

Press Run to start the program, or Step to do one block at a time.

Loading the blocks…

What you should see

In the spiral, side starts at 10 and the loop runs 20 times, changing side by 10 at the end of each round. How long is the last line the turtle draws?

Pick an answer to see why.

Plan, then build

The quiz and the guessing game were designed before they were built. For a program of your own, plan the same way:

  1. Say what it should do, in a sentence or two. What does it ask? What does it decide? What does it say at the end?
  2. List the variables, each with its type and what it holds, in a table like the one for the guessing game.
  3. Write the steps in plain words, with the choices as “if … then … otherwise …”.
  4. Choose tests: inputs whose right answers you know, including the edges of every condition.
  5. Build it one part at a time, running it after each part. Then run all your tests.

Try it

Free play: every block

Build your own program here. Your blocks are kept in this browser.

What the program says and asks appears here.

name – no value

Press Run to start the program, or Step to do one block at a time.

Loading the blocks…

You are planning a game. Which should you write first?

Pick an answer to see why.

In short

Exercise

What does change lives by -1 do when lives holds 3?

Pick an answer to see why.

Which of these is a condition?

Pick an answer to see why.

name holds “Asha” and age holds 13. What does join name age make?

Pick an answer to see why.

A program says if temp > 30 then say “Hot!” and nothing else. temp holds 25. What happens?

Pick an answer to see why.

Which tests best check a rule “free entry for children under 10”?

Pick an answer to see why.

a.

Explain each term with an example: variable, input, condition, selection.

Answer
b.

What is the difference between set and change? A variable coins holds 8. What does it hold after set coins to 3, and what after change coins by 3 (each starting from 8)?

Answer
c.

Name the data type (number, text or true/false) best suited to each variable, and give a reason for one of them: a student’s name; the number of students in a class; whether the school bus has left; the price of a notebook; a district’s name; whether a player has a ticket.

Answer
d.

x holds 6 and y holds 9. Is each condition true or false? i. x < y ii. x > 6 iii. y = 9 iv. x + 3 = y v. y < x

Answer
e.

Write a trace table for this program when the user types 7. What does it say?

ask “Pick a number” and keep the answer in nset total to n × 2if total > 10 then    change total by -10else    change total by 5say total
Answer
f.

A canteen gives a free banana with any order of Rs 100 or more. Rojan writes: if bill > 100 then say “Free banana!”. Find the bug, give an input that shows it, and fix it.

Answer
g.

Design a program that asks for a student’s marks out of 100 and says “Distinction” for 80 or more, “Pass” for 40 to 79, and “Not yet” below 40. List its variables with their types, write its blocks in plain words, and give five tests with the answers they should give.

Answer
h.

Look at this quiz program. What is wrong with it, and what will a player see if they play two games in a row and answer right both times? How would you fix it?

ask “What is 9 × 7?” and keep the answer in answerif answer = 63 then    change score by 1say join “Score: ” score
Answer
i.

Plan a game of your own that uses at least three variables of at least two different types. Write: what the game does, a table of its variables (name, type, what it holds), its steps, and three tests.

Answer
j.

Why do programs need input and if/else? Explain with an example of an app you have used.

Answer