Lesson 8: Guess the number
About this lesson
This is the eighth in a series of lessons to transition from visual coding to text-based coding with a general-purpose programming language.
Year band: 5-6, 7-8
Curriculum Links AssessmentCurriculum Links
Links with Digital Technologies Curriculum Area
Strand | Year | Content Description |
---|---|---|
Processes and Production Skills | 5-6 |
Design algorithms involving multiple alternatives (branching) and iteration (AC9TDI6P02). |
7-8 |
Design algorithms involving nested control structures and represent them using flowcharts and pseudocode (AC9TDI8P05). Trace algorithms to predict output for a given input and to identify errors (AC9TDI8P06). |
Assessment
Students undertake a self-reflection of the programming task. The teacher can use the completed self-assessments to assist in summative assessment.
In assessing code in languages like Python or JavaScript, consider a rubric that brings in important skills for general-purpose programming.
Learning hook
The Rubik's Cube was invented in 1974, and is still a popular puzzle today.
There are a number of solutions to the Rubik’s Cube, each involving a sequence of steps. In the Rubik's Cube video, the Lego robot solves the cube using one of these sequences, with a colour sensor to monitor the colours while working. However, the Rubik's Cube can even be solved blindfolded! By repeating a sequence of steps enough times, the solution can be reached even without looking at the colours.
A sequence of steps to solve a problem is referred to as an algorithm.
Invite students to play this game in pairs:
- Think of a number between 1 and 20. Don’t tell your partner.
- Now, ask your partner to guess the number.
- If they get it wrong, tell them to go ‘lower’ or ‘higher’ and try again. If they get it right, the game is over.
Ask:
- What’s the quickest way to win this game as the guesser? What number would you start with?
- What would be your next guess if you were told to go ‘higher’, or ‘lower’?
Students can write this game out as a simple algorithm (flowchart or pseudocode is not necessary).
Guess 10 (halfway between 1 and 20).
If told higher, ignore the numbers 1 to 10, and guess halfway between 11 and 20.
If told lower, ignore the numbers 11 to 20, and guess halfway between 1 and 9.
Keep repeating this process, throwing out the irrelevant numbers and guessing halfway between what’s left.
The solution is an algorithm called a binary search. For an example of a binary search, view The famous phonebook video clip.
Learning map and outcomes
In this lesson, students will:
- access an online programming environment for visual code (Scratch) and for general-purpose programming (Python or JavaScript)
- code a higher/lower game, where the player must guess a secret number between 1 and 20
- tinker with the game to make it more challenging.
Learning input
Begin by watching the video demonstrating the higher/lower game, which uses loops and variables:
Now, examine the Pseudocode below carefully, then answer the questions below it:
BEGIN answer ← 0 Repeat While answer != 12 answer ← Input ‘How many months are in a year?’ End Repeat Display ‘You got it!’ END
QUESTIONS:
- What question does the program ask the user?
- How many times will the question be asked?
- What happens once the loop ends?
Two types of loops
In Lesson 7, two types of loops were introduced: while and for.
A while loop is like an if-then structure, except the code inside repeats as long as the condition is met.
Examples:
- repeat while the user has not entered the correct password
- repeat while the enemy is still alive
- repeat while we have time left to win
- repeat while a number hasn’t reached a target (this one is normally done with a for loop)
The closest Scratch equivalent is the repeat until block, but its logic is opposite. It repeats until a condition is met, not while a condition is met.
A for loop is specialised for counting. The code inside repeats a certain number of times.
The counter (also called the index variable) changes each time the loop runs. It can be used to pick each item's position as the loop works through an array.
Examples:
- repeat a message 10 times
- produce a series of numbers from 1 to 10
- produce a countdown from 10 to 1
- access each item in an array
The closest Scratch equivalent is the repeat block, but it is less flexible and does not provide access to the counter.
- ‘How many months are in a year?’
- The question keeps getting asked until the user enters the right answer. It could go forever!
- Once the loop ends, the program displays ‘You got it!’
Here is a more complex version of the program. Read it carefully, then answer the questions.
BEGIN answer ← 0 tries ← 0 Repeat While answer != 12 And tries < 3 answer ← Input ‘How many months are in a year?’ tries ← tries + 1 End Repeat If answer = 12 Then Display ‘You got it!’ Else Display ‘You ran out of tries.’ End If END
QUESTIONS:
- What is the purpose of the new variable 'tries'?
- In this version the loop may end even if the user doesn’t get the right answer. Why?
- Why is the IF-THEN-ELSE structure needed at the end of the program?
- The variable 'tries' keeps the number of attempts the user has made to enter the right answer.
- A second condition has been added to the WHILE loop. The loop will now stop after three attempts. It also still stops if the user enters the right answer.
- Once the loop ends, we need to check once more if the user got the answer right. It’s possible the loop ended after three unsuccessful attempts.
Learning construction
For more on setting up and choosing a language, see Setting Up.
Step 1: Solution development
The video 'Guess the number' demonstrates coding the solution in Scratch, Python and JavaScript. Try it yourself before checking the solution code.
By now, you have probably noticed that some coding ‘rules’ seem to matter more than others. Here are some examples of rules versus conventions:
Rule (Do this or you will likely cause a syntax error or a bug in your program!) |
Convention (Do this for code readability, but some programmers may disagree.) |
Use round brackets with display commands. For example: Python: print("Hello") JavaScript: document.write("Hello"); |
Use single quotes inside display commands. Double quotes also work. For example: Python: print("Hello") JavaScript: document.write("Hello"); |
In Python, indent code inside structures. For example if (10 > 5): print('Of course!') |
In JavaScript, indenting is strongly recommended. Indented: if (10 > 5) { document.write('Of course!'); } Not indented: if (10 > 5) { document.write('Of course!'); } |
In JavaScript, use var (or let) to declare variables. (There is a subtle difference between var and let, important once you make complex programs. You can learn more here.) |
Use ‘camel case’ for variable names. For example: myName, orderTotal, noOfStars Some Python coders prefer underscores: my_name, order_total, no_of_stars |
Use == for comparison of two numbers, never a single = sign. For example: Python: if (rating == 5): print('5 stars!') JavaScript: if (rating == 5) { document.write('5 stars!'); } |
Include spaces in Maths statements.
Often, they’ll work without spaces. For example: Python: if ( rating==5): print('5 stars!') JavaScript: if (rating==5) { document.write('5 stars!'); } |
As with spoken languages, some rules used to be universally accepted as strict, but now are sometimes ignored, such as using semicolons (;) at the end of code lines in JavaScript. Whether this will cause a syntax error may depend on the coding environment being used.
Finally, some conventions are just habits. For example, programmers often use the name i for the index variable in loops, because ‘i’ is short for ‘index’. But you could use another letter like n, or a word like index for the variable name.
Solution Code
Step 2: Tinker task
First, change the range for the secret number from 1–20 to a higher number; for example 1–50.
Next, modify the game so that the player only gets a maximum of guesses; for example 5 - otherwise they lose. The higher/lower game already records the number of guesses the player makes.
Solution Code
Challenge
These challenges use the skills covered so far. By writing or modifying their own programs, students have an opportunity to demonstrate Application and Creation.
Challenge 1
Design and code a program to provide a cumulative total as prices are entered, until the user chooses to stop. See the sample output below:
Welcome! Enter your first price: 17 The total so far is $17. Enter another price, or enter STOP to finish: 5 The total so far is $22. Enter another price, or enter STOP to finish: 12 The total so far is $34. Enter another price, or enter STOP to finish: STOP Thank you for using this program.
a. Prepare pseudocode first.
BEGIN total ← 0 Display ‘Welcome! Enter your first price: ’ price ← input from user Repeat While price is not equal to ‘STOP’ total ← total + price Display ‘The total so far is $’, total, ‘.’ Display ‘Enter another price, or enter STOP to finish: ’ price ← input from user End Repeat Display ‘Thank you for using this program.’ END
b. Code the program in Python or JavaScript.
Challenge 2
Code a vowel replacer program by following the video below.
Challenge 3 (OPTIONAL)
Ask your students to write a higher/lower game where the roles are reversed. The human player thinks of a secret number, and the computer must guess the answer.
Here are some prompt questions to help students develop their pseudocode:
- What input and output will be required? How will the user tell the computer to go higher or lower? (This is a useful program to design as a class, especially for a device like the BBC micro:bit with limited inputs available to the user.)
- How will the computer reach the correct number? See our discussion of binary search at the beginning of this lesson. Note, after your calculation you will need a way to round down to the nearest whole number. To do this, you can use the int() command in Python and the parseInt() command in JavaScript.
- What things will the computer need to remember as it works toward the correct number? These will need to become variables in the program.
Resources
- Setting up online environments
- Online environments for coding in each language
- Cheat sheets listing basic commands for coding:
- Python Cheatsheet (from Grok Learning)
- JavaScript CheatSheet (Tip: Press the little blue tabs to move Variables, Basics, Strings and Data Types to the top.)