Block 2 Part 4 Loops OU Online PDF

Summary

This document is a part of a course on programming, specifically focusing on loops. It provides examples and activities for understanding different types of loops in the OUBuild programming environment. It includes activities and questions encouraging critical thinking about programming logic, repetition, and conditions.

Full Transcript

17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Unless otherwise stated, copyright © 2025 The Open University, all rights reserved. Printable page generated Friday, 17 Jan 2025, 01:37 Block 2 Part 4 Loops I...

17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Unless otherwise stated, copyright © 2025 The Open University, all rights reserved. Printable page generated Friday, 17 Jan 2025, 01:37 Block 2 Part 4 Loops Introduction Humans may get tired of repeating the same thing over and over, but computers are ideally suited to repetitive tasks. All programming languages include structures for causing instructions to be executed repeatedly. As you learned earlier, such structures are known as loops. Repeated execution is often referred to as repetition or looping. In OUBuild, when a program encounters a loop, it executes (runs) each of the blocks inside the loop – the loop contents – before ‘looping’ back to the top and beginning all over again. There are three general types of loop: 1. loops whose contents execute a fixed number of times 2. loops whose contents execute indefinitely (potentially forever) 3. loops whose contents execute repeatedly dependent on some Boolean condition. You have already encountered the first two types of loop in the form of the OUBuild looping blocks repeat[]{} and forever{}. In this part, you will review these two types of loop and look at some further ways to use them. You will also be introduced to loops that are controlled by a Boolean condition, known as conditional loops. Sections 4.1, 4.2 and 4.3 are based around activities in which you will be introduced to the main new programming ideas of this part. At this stage, we expect that you will be able to understand some scripts without detailed explanation. However, it’s certainly not always possible to tell at a glance what an unfamiliar script does, so remember the techniques that may help, such as: observing variable watchers as a script executes step-by-step execution – temporarily breaking the script apart and running it in separate chunks. In Section 4.4, you will turn to problem-solving in the context of looping – that is, considering problems that can be solved by creating programs involving loops of some kind. You will learn how to progress from a program specification via a suitable algorithm involving loops to a working script. You will also learn techniques for testing and debugging such scripts. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 1/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Then, in Section 4.5, you will practise using your problem-solving skills and applying the programming ideas in creating a small game. Activity 4.1 (exploratory) This activity introduces you to a program involving conditional loops, which we will refer to as Hare and Tortoise, and which you may choose to develop further in Section 4.5. Open the project Activity_4.1.sb2 from the Part 4 folder. This project contains four sprites: Hare, Tortoise, Start Line and Finish Line. Each of Hare and Tortoise have two costumes, depicting different phases of movement. Code is provided for Hare and Tortoise. Start the program with the green flag. This program is a partially-complete animation inspired by the fable of The Hare and the Tortoise. In the fable, the slow-moving tortoise and the faster hare run a race. The tortoise wins with its steady plodding as the hare falls asleep mid-race. In this partial animation, however, the hare and the tortoise simply move at the same pace from the start to the finish as the Hare and Tortoise sprites have identical when_green_flag_clicked scripts. You aren’t expected to understand the details of this program yet; we just want you to get a general sense of the kind of repetition involved. Over to you Look at each of the when_green_flag_clicked scripts. As always with OUBuild, the block names give a good indication of their purpose. On this basis, can you identify the code that causes the animated movement of each sprite to be repeated until the finish line is reached? Reveal solution 4.1 Forever loops and conditional loops In this section, you will review the use of loops formed using the forever{} block, which we refer to as a forever loop. You will see how, despite the loop’s name, OUBuild may actually be instructed to stop running such a loop. You will then be introduced to the concept of a conditional loop. 4.1.1 Forever loops Activity 4.2 (exploratory) https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 2/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Open the project Activity_4.2.sb2 and save it as Activity_4.2_sol.sb2. In this program, the Owl sprite will be made to fly repeatedly around the stage. You can see that a custom block fly has been defined; try it by clicking on the define[fly] script. (In this project, the block fly makes Owl appear to fly a little further and faster than the block of the same name in Part 3. It does this by having Owl take more steps in each move and pause for less time between moves.) Two scripts are provided for Owl that you will work with in due course. There are two other sprites in the project: Tree, on which Owl may sit Bat, encounters with which increase Owl’s size. (a) A sprite’s size can be manipulated and reported by blocks from the Looks palette, shown in Figures 4.2 and 4.3. Explore them. Figure 4.2 Figure 4.3 Note that these blocks function using a percentage of the sprite’s original size (the size at which the sprite was created). So change_size_by, for example, always increases the sprite’s size by 10% of its original size. (b) We have provided a when_green_flag_clicked script that makes Owl do the following: glide to Tree appear in front of other sprites appear to sit set its size to 100% of its original size https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 3/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online say 'Press your spacebar to make me fly'. Explore the blocks in this script and run it a couple of times with Owl starting in different positions. (c) Over to you Suppose that background music should be played whilst the program runs. Choose a piece of music from the Sound Library and create a second when_green_flag_clicked script which simply plays the background music indefinitely, using a forever{} block from the Control palette. Can you see why a second when_green_flag_clicked script is required? Reveal solution (d) Now turn to the when[space]key_pressed script provided. Over to you What does this script do? Reveal solution (In this project Owl’s rotation style is set to ‘fixed’ so its image does not appear to rotate or be reflected.) (e) Run the when[space]key_pressed script a few times and experiment with stopping it – hence ending Owl's flight – in the following ways: clicking on the script itself clicking the red stop icon running a stop[] block from the Control palette with input all, shown in Figure 4.5. (You met the stop[] block in Part 3 Section 3.3.) https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 4/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Figure 4.5 (f) Suppose now that if Owl encounters Bat whilst flying around in response to the spacebar being pressed, Owl should: say 'Yum yum' increase its size by 20% glide to Tree appear to sit. Once Owl is sitting in Tree it should stay there, until the spacebar is pressed again, but the background music should continue. There are several ways in which the when[space]key_pressed script could be amended to achieve this. One is to include an ifthen{} block with Boolean condition touching[Bat]? ; and (in the ‘if’ part) a stop[] block with input this_script, as shown in Figure 4.6. Create this now. Figure 4.6 Try it out, both by running it alone and by running it as part of the overall program, having first clicked the green flag. Note that when Owl encounters Bat the when[space]key_pressed script, and only that script, stops. (g) https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 5/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Change the input of the stop[] block to all, as shown in Figure 4.7, and try the program again. Figure 4.7 Note that, in this case, all scripts are stopped when Owl encounters Bat, including the one playing the music. (h) Here we have a situation in which blocks should be run, making Owl fly, until a particular condition holds (Owl encounters Bat). A neater way to implement code in this sort of situation is with the repeat_until{} block shown in Figure 4.8. Figure 4.8 Drag it from the Control palette and consult its help information. This block implements a conditional loop: one whose contents are run repeatedly until the loop’s Boolean condition – in its input box – reports 'true'. Here: the condition of interest is Owl encountering Bat, which can be checked by the Boolean condition touching[Bat]? the blocks that should be run until this condition reports 'true' are those implementing the flying. Dismantle your when[space]key_pressed script and reassemble it as shown in Figure 4.9. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 6/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Figure 4.9 The loop contents are run repeatedly until the Boolean condition touching[Bat]? reports 'true'. When this happens, Owl has encountered Bat and so, according to the specification, Owl should say 'Yum yum', etc. The blocks implementing these subsequent actions are therefore placed after the loop, so that they are run once the loop has finished executing. Over to you i. What happens if you drag Owl on top of Bat and then press your spacebar? Why does this happen? ii. What happens if you hide Bat and then press your spacebar? Why does this happen? (To hide Bat, ensure Bat’s thumbnail is selected below the stage and then either run a hide block (in the Looks palette) or deselect ‘show’ in Bat’s information pane.) Reveal solution With Bat visible again (run a show block or use Bat’s information pane), try out the when[space]key_pressed script as part of the entire program: start the program with the green flag and then press your spacebar. Press it again each time Owl returns to Tree. You should see Owl’s size increasing with every Bat encounter. (Observe the value displayed by Owl’s size watcher.) (i) You will finish by implementing the end of the animation. Suppose that, having returned to Tree, if Owl’s size exceeds 140 (having eaten too many bats, perhaps), then it should: https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 7/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online say 'Goodnight' disappear and the program should end – that is, the music should stop playing. Over to you Add a selection block to the end of your when[space]key_pressed script to achieve this. Use also the following blocks: size hide stop[]. Reveal solution (j) Finally, now that Owl disappears at the end of a game, it needs to be made to reappear at the beginning. Over to you Add a block to the original when_green_flag_clicked script to achieve this. Reveal solution A completed program is provided in Activity_4.2_completed.sb2. Further discussion Forever loops Forever loops – loops whose contents run over and over, indefinitely – are used in programs that are expected to continue executing for an indefinite period of time. They are sometimes referred to as infinite loops though in fact they can, as you have seen, be stopped. Many programs you interact with every day use such loops – web servers, your computer’s operating system, and so on. Forever loops in OUBuild are typically used to implement tasks that should continue indefinitely throughout a program – for example, implementing continuous background sound, or continuous sprite movement. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 8/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online OUBuild implements loops that execute forever with the forever{} block, shown in Figure 4.12. Figure 4.12 forever{} is a foot block: nothing can be attached underneath it. It runs indefinitely, therefore no code can sensibly follow it. As its name suggests, the blocks inside a forever{} block’s jaws – the loop contents – are repeatedly run, indefinitely. A flow chart illustrating the forever{} block is very simple, as shown in Figure 4.13. Figure 4.13 However, as you have seen, a forever loop can in fact be stopped in various ways, including when a stop[] block is run, stopping the script that contains the forever loop. Suitable incorporation of a stop[] block into a program enables a forever loop to be stopped intentionally as an aspect of a program – for example, stopping background music once a game or animation ends. stop[] blocks stop[] blocks can be used to control the execution of scripts within a program. A stop[] block takes one of three possible input values, as follows: 1. all: stops all scripts in the program 2. this_script: stops just the script that contains this block 3. other_scripts_in_sprite: stops all other scripts in the sprite concerned, except the one that contains the stop[] block. 4.1.2 Conditional loops In Part 3 you met Boolean blocks and their use as Boolean conditions for ifthen{} and ifthen{}else{} blocks. Just as OUBuild can use a Boolean condition to determine whether or not to execute a particular set of instructions, it can also use a Boolean condition to determine whether or not to execute a loop’s contents. Loops that work like this are called conditional loops. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 9/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online OUBuild implements conditional loops with the repeat_until{} block from the Control palette, shown in Figure 4.14. Figure 4.14 As you have seen, the repeat_until{} block contains a hexagonal recess into which its Boolean condition is placed. The repeat_until{} block instructs OUBuild to keep executing its contents – the blocks between its jaws – until the Boolean condition reports 'true'. When OUBuild encounters a repeat_until{} block, it first checks the value of the Boolean condition. If it is 'true', then the loop contents are not run at all and OUBuild moves on to any blocks after the repeat_until{} block. If it is 'false', the loop contents are run, from the first block to the last, and then OUBuild again checks the value of the condition. If it is now 'true', then the loop contents are not run again and OUBuild moves on to run any blocks after the repeat_until{} block; if it is 'false', then the loop contents are run again, and so on. Before each potential run of the loop contents, OUBuild checks the condition to determine whether or not to run the loop contents. A flow chart illustrating how a repeat_until{} block works is shown in Figure 4.15. Figure 4.15 As you saw in Activity 4.2 part (h), if a conditional loop’s Boolean condition reports 'true' when OUBuild first reaches the loop, then the loop contents are not run at all. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 10/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online At the other extreme, if its Boolean condition reports 'false' when the loop is reached and continues to report 'false' after every run of the loop contents, then looping never stops: the loop contents are run repeatedly, indefinitely. In effect, the loop acts like a forever loop. Depending on the precise requirements, it can therefore be necessary to consider carefully: 1. whether and how to ensure that loop contents are run at least once – that is, that the loop’s condition reports 'false' initially 2. whether and how to ensure that loop contents are not run indefinitely – that is, that the loop’s condition reports 'true' at some point. You will learn more about how to do this in later activities. You have seen how a repeat_until{} block can be used for moving a sprite until it collides with another sprite. In the next activity, you will see how it may be used to enable user input to be entered repeatedly until it is of a required form. In Part 3 you learned various techniques for checking user input. For example, you created scripts checking: whether a user’s number is equal to, less than, or greater than a secret number in a guessing game whether a user’s proposed password is valid, for example, has a required length or contains certain characters at specific positions whether a password entered by a user matches a stored password. However, each script in Part 3 only allowed the user one attempt at entering input of the required form. In reality, programs often allow users to make several – perhaps even unlimited – attempts at getting the input right. You will now see how this may be achieved, in the context of another small number game. Activity 4.3 (exploratory) Open the project Activity_4.3.sb2 and save it as Activity_4.3_sol.sb2. In this project, we have implemented a small quiz using two scripts. In essence, the user is told two numbers and asked for their mean (their average). You are going to amend the program to allow the user multiple attempts at getting the mean right. (a) Explore the when_green_flag_clicked and when[space]key_pressed scripts provided. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 11/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online The when_green_flag_clicked script generates two random numbers and creates a string asking for the mean of the numbers. The when[space]key_pressed script uses this string to ask the user for the mean, compares the user’s attempt with the actual mean and informs the user whether or not their attempt is correct. Try out the scripts by running the program: start the program with the green flag and follow the instructions. Note that you can make multiple attempts at the mean by repeatedly pressing your spacebar. (b) You will amend the when[space]key_pressed script to allow the user multiple attempts at the mean without having to repeatedly press their spacebar. Let’s begin by supposing that the user should be allowed to continue making attempts at the mean until their attempt is correct. A repeat_until{} block can be used to implement this. Over to you Create a repeat_until{} block with a suitable Boolean condition ready to be used in the script, but don’t add it yet. The Boolean condition should check whether the user’s attempt equals the mean. Reveal solution (c) Once the Boolean condition reports 'true', the loop will end. At this point, the user has entered the correct mean and the script should tell them so. This subsequent action can be implemented as shown in Figure 4.17; add this block now. Figure 4.17 Combining the looping block with the request for user input requires a little more thought. There are a few ways to do it. Below is one way to start that might initially seem quite reasonable but is not quite right, as you will see. Amend the when[space]key_pressed script as shown in Figure 4.18 (removing the ifthen{}else{} block) and run it a few times, observing the values of the variables. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 12/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Figure 4.18 There are a couple of problems you might have identified with this script. The most obvious is that when the user makes an incorrect attempt, they aren’t informed that the attempt is wrong; they are simply repeatedly asked the same question. You might also have realised that there is a more subtle problem that would only occur if, in two successive games, the mean happened to be the same both times. Suppose, for example, that in the first game the random numbers were 8 and 12, and then in the second game the numbers were 7 and 13. Then the value of mean both times would be 10. In the first game, when the user enters the correct mean (10) the game ends with mean_attempt having value 10. When the next game starts, mean_attempt still has value 10 and so, again, we are supposing, does mean. Hence the loop condition [mean_attempt]=[mean] immediately reports 'true', the loop contents are not run at all, and the user is not asked the question. Though unlikely, this is possible, and we must deal with it. (d) There are various ways to address these issues. We will do it by using separate code, before the loop, to ask the initial question and to get the user’s initial attempt, as shown in Figure 4.19. Amend your script now and try it out. Figure 4.19 https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 13/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online With this code: 1. the loop contents will be run only when the user has made an incorrect attempt, and so the code in the loop contents can inform them of this fact 2. the user is always asked the question at least once, whatever value mean_attempt might have had at the end of the previous game. (e) Now let’s suppose that a limit is imposed: the user may make no more than three attempts. After three incorrect attempts, the user should be informed that they may make no further attempts. A count will need to be kept of the number of attempts, so start by creating a variable attempt_count. Over to you Now use attempt_count to amend your when[space]key_pressed script as follows: i. As soon as the user has made their first attempt, attempt_count should be set to a suitable initial value. Add a block to do this. ii. On each subsequent attempt, attempt_count should be increased by 1. Add a block to do this. iii. The loop contents should run repeatedly until either the user has attempted correctly or the user has made three attempts. Change the loop’s condition to achieve this. Reveal solution (f) We’re not quite done, however – as you’ll see if you run the script and make three incorrect attempts. You’ll be informed that you were correct. The problem is that it is no longer necessarily the case that, once the loop ends, the user has made a correct attempt. The loop may have ended because the user made three incorrect attempts. One way of handling this is to check the user’s final input – that is, the value of mean_attempt, after the loop, as shown in Figure 4.21. Do this now and try out your complete script. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 14/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Figure 4.21 A completed program is provided in Activity_4.3_completed.sb2. Further discussion Using conditional loops When something must happen repeatedly until a particular condition holds, a conditional loop may be used, with the ‘something’ as the loop contents. Suppose something further must then happen when the condition holds. The ‘something further’ may be implemented by blocks directly after the loop. Once the condition holds, the loop stops and OUBuild moves on to run the blocks after it. If the loop condition is a compound one, then subsequent code may be needed to check which component of the compound condition caused the loop to terminate, before deciding on the subsequent action. For example, in Activity 4.3 code was needed to check whether the user had made a correct attempt or had made the maximum number of incorrect attempts. Checking user input In Activity 4.3, you used a conditional loop to enable the user to make multiple attempts at entering the correct number, but the techniques involved can be easily adapted to other input-checking requirements, as Activity 4.4 illustrates. Conditional loops have a range of potential uses. In the rest of this block, you will encounter some other ways of using them. Activity 4.4 (self-assessment) Consider the stack shown in Figure 4.22. Think through what it does and how, but do not create it unless you are stuck. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 15/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Figure 4.22 Maximise a. What happens when the selection block at the end of the stack is reached in a case where the user makes three invalid entries and then a fourth, valid, entry? b. What happens when the selection block at the end of the stack is reached in a case where the user makes four invalid entries? 4.1.3 Conclusion Activity 4.5 (exercise) Open the project Activity_4.5.sb2 and save it as Activity_4.5_sol.sb2. The when[space]key_pressed script provided calculates the user’s speed in a 400-metre race. Amend it to ensure that the user’s input is positive, as follows: ask the user to enter their time in seconds repeatedly, until their entry is positive, tell the user: 'Times must be positive. Enter your time in seconds' tell the user their speed in m/s rounded to one decimal place. (You should assume the user enters a number; the only check your script should carry out is whether the number is positive.) Reveal comment In this section, you have revised and extended your knowledge of forever loops, and been introduced to conditional loops and their use in enabling repeated user input. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 16/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online 4.2 Fixed loops and string processing In this section, you will revise and extend your knowledge of loops formed using the repeat[]{} block, which we refer to as fixed loops. 4.2.1 Fixed loops As you know, the repeat[]{} block, shown in Figure 4.24, instructs OUBuild to run the blocks inside its jaws – the loop’s contents – a specific number of times, given by the value in its input box, which should be a non-negative integer. Figure 4.24 Once the contents have been executed the specified number of times, OUBuild moves on to the next block, as illustrated in the flow chart in Figure 4.25. Figure 4.25 Until now, whenever you have used this block, it has been with a number entered directly as its input value, such as shown in Figure 4.26. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 17/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Figure 4.26 The input value of 12 in the script in Figure 4.26 means that each time this script executes, the loop contents are run 12 times. The number 12 is entered by the programmer, so it is determined in advance of the program running. However, a fixed loop can also be used more flexibly to run blocks a fixed number of times in cases where that number cannot be determined in advance. For example, it may depend on data entered by the user. Another way to adapt fixed loops (and in fact other kinds of loop) is to use variables within their contents. That way, the contents can depend on data that may vary. This is the basis of some useful techniques for processing strings (as you will see in this section) and lists (as you will see in the next section). In Activity 4.6 you will start to use fixed loops in these more flexible ways. In analysing these possibilities, we will need to examine the effect of individual runs of a loop’s contents and will need in particular to distinguish between running the loop as a whole and the individual runs of the loop contents which occur as part of this. We will use the term iteration to refer to a single run of the loop contents. Activity 4.6 (exploratory) Open the project Activity_4.6.sb2 and save it as Activity_4.6_sol.sb2. There are two sprites in this project: Owl and Tree. The scripts provided make Owl perform a simple aerobatic display, returning to sit in Tree each time. You will amend the program to achieve different aerobatic effects. (a) Look at the scripts provided, as directed below. (i) https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 18/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online The when_green_flag_clicked script ensures that when the program starts, Owl sits in Tree, pointing up (that is, its direction is 0 degrees). (ii) Aerobatic displays involve Owl flying in a straight line. This is the effect of the custom block fly (which was also used in Activity 4.2). Displays also involve Owl flying back again, which is the effect of the new custom block fly_backwards: it has the reverse effect to fly, as you can see from its definition, which uses negative inputs (–20) to move[]steps blocks. (iii) We will consider in detail the when[space]key_pressed script, shown in Figure 4.27. Figure 4.27 Start the program with the green flag, then run this script. Owl flies out and back four times, first up, then to the right, then down, then to the left, ending up sitting back where it started. It performs a symmetrical four-pointed star display. This display is achieved by the loop contents running four times, according to the input value 4. The iterations (runs) of the loop contents do the following: The first iteration flies Owl up (since Owl is initially pointing up) and back, and then turns it clockwise 90 degrees to point to the right. The second iteration flies it right and back and then turns it clockwise 90 degrees to point down. The third iteration flies it down and back and then turns it clockwise 90 degrees to point left. The fourth iteration flies it left and back and then turns it clockwise 90 degrees to point up. (We have set Owl’s rotation style to fixed so its image does not appear to rotate or be reflected.) Owl ends up pointing in its initial direction, up, since altogether it turns clockwise 90 degrees four times, which is a total of 360 degrees: a full circle. This way, when this script is run again, Owl performs exactly the same display. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 19/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online (b) A slightly different display would be achieved by turning Owl, say, 60 degrees six times, so that Owl flies out and back six times – performing a six-pointed star display – returning to its starting position and direction. Over to you Amend the when[space]key_pressed script to achieve this. Reveal solution (c) The key to a consistent symmetrical display each time the spacebar is pressed is that the number of iterations multiplied by the amount turned in each iteration should equal 360. To see this, try the script with 5 as the input to the repeat[]{} block, and a turn of 60 degrees within the contents of the block. Owl ends up with a different direction each time, and so in successive displays – if the script is run again and again – follows a different path. With five iterations, for a consistent symmetrical display each time, the number of degrees turned should be 360/5, that is, 72. Try this and see the difference. (d) We can use this relationship between the number of iterations and the number of degrees turned in each iteration to amend the script to allow the user to decide the number of points to the star – that is, the number of iterations. We will use a variable number_of_points to provide the input to the repeat[]{} block. This variable will be set to the number entered by the user. Amend your script to do this, as shown in Figure 4.29. It’s not yet complete as you have still to deal with the number of degrees turned in each iteration. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 20/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Figure 4.29 You have seen that the number of iterations multiplied by the number of degrees turned in each iteration should be 360. To achieve this, the number of degrees turned in each iteration should be 360 divided by the number of iterations. Over to you Complete the script by inserting a number block from the Operators palette, with appropriate inputs, into the input box of the turn_clockwise[]degrees block. Reveal solution (e) The repeat[]{} block in Figure 4.30 takes a variable as its input, allowing the number of iterations to vary according to the value of that variable. It also uses that variable within its contents; its value being used to determine the number of degrees turned in each iteration. Note that in each iteration the variable has the same value, giving rise to the same number of degrees. However, some interesting possibilities arise with fixed loops whose contents involve a variable whose value changes as the iterations progress. That is what we turn to now. Let’s suppose that, once Owl has performed its display and is sitting back in the tree, it should finish by: counting backwards from 10 to 1, saying each number in turn saying 'Blast off!' flying up until it reaches the top of the stage. We will concentrate first on the countdown. It could be achieved using a sequence of ten blocks, starting as shown in Figure 4.31. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 21/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Figure 4.31 However, the actions involved – simply saying a number – are repeated, and so as you might expect, a loop provides a more elegant and flexible solution. (i) It will help first to consider a simpler scenario: counting up the numbers from 1 to 10. We can do this by using a loop with 10 iterations and a variable – let’s call it number_to_say – used to make Owl say a different number in each iteration. So: in the first iteration, number_to_say should have value 1 in the second iteration, number_to_say should have value 2 … and so on, until: in the tenth iteration, number_to_say should have value 10. This can be achieved by having the loop contents do the following: use number_to_say to say the current number then increase the value of number_to_say by 1, ready to be used in the next iteration to say the next number. If we arrange that number_to_say starts with value 1, and that there are 10 iterations, then the successive iterations will say the numbers from 1 to 10 as required. The stack shown in Figure 4.32 does this; create and run it. Figure 4.32 It is important to understand how this code works since it is the basis of many useful techniques with loops. You might picture the changing value of number_to_say, and the text displayed in each iteration, something like that shown in Figure 4.33. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 22/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Figure 4.33 Notice that number_to_say ends up set to 11, but this doesn’t matter, as this final value is not displayed. (ii) Now we’re going to use a similar idea, but with the value of the variable decreasing in each iteration, to create a stack that makes Owl count down the numbers from 10 to 1. Try to form a mental image of how the process might work before starting to create code; if you find Figure 4.33 helpful, you might form the sort of mental image shown in Figure 4.34 to guide you. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 23/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Figure 4.34 Over to you Create a stack that makes Owl count down the numbers from 10 to 1. Then add the stack to the end of your when[space]key_pressed script. Be sure to initialise your variable appropriately. Reveal solution (iii) Over to you Finally, add blocks to the end of your when[space]key_pressed script so that once Owl has performed its display and is sitting, it performs the countdown from 10 to 1 and then: says 'Blast off!' flies up until it reaches the top (that is, the edge) of the stage. A conditional loop will be required for the final step. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 24/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Reveal solution A completed program is provided in Activity_4.6_completed.sb2. Further discussion Loops with variable inputs and contents In Activity 4.6, you saw how a fixed loop may take a variable as input, enabling different numbers of iterations according to the value of the variable. For example, the value may be entered by the user. This means that the fixed looping achieved by a repeat[]{} block is more adaptable than the name suggests. The number of iterations is not necessarily ‘fixed’ when the program is created. You also saw that a loop’s contents may involve a variable whose value may be different in different iterations, such as in the stack shown in Figure 4.37. In this example, in each iteration, the variable is first used (to say a number) and then increased by 1 (ready for the next iteration). Figure 4.37 The idea of having a variable initialised to a suitable value, with each iteration both using and changing the variable’s value, is very important. As you will see in subsequent activities, this idea is the basis of some powerful techniques. As Activity 4.7 indicates, there are often different ways to use this idea in achieving the same thing. Activity 4.7 (self-assessment) Consider the stack in Figure 4.38, but don’t create it unless you are stuck. Figure 4.38 https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 25/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online What would be displayed when it is run? 4.2.2 String processing In the next activity, you will see some applications of the idea of having a variable initialised to a suitable value, with each iteration of a loop both using and changing the variable’s value. You will create scripts to perform some simple processing of text in the form of a single string. These processes all involve repeatedly carrying out some action on the characters in the string. Think of these as prototypes for more sophisticated text-processing programs. In OUBuild, text may alternatively be held in a list, which you will consider in the next section. Text processing Text processing refers to the manipulation of text – words – by a computer. Text may need to be manipulated in many different ways. Think of a word processor, for example, which, given a piece of text, might: search for the first occurrence of a specific word or character replace every occurrence of a specific word or character with another insert a character according to a particular rule, for example, a space after each full stop search for all invalid ‘words’, that is, words that don’t appear in a dictionary and so on. Activity 4.8 (exploratory) Open the project Activity_4.8.sb2 and save it as Activity_4.8_sol.sb2. Scripts are provided that you will look at in due course. (a) Run the when[a]key_pressed script provided. It applies a decorative effect to a five-letter word entered by the user, with stars (asterisks) added at the beginning and end and between each pair of characters. (Of course, the script works whatever five characters are entered by the user, whether or not they constitute a word in English.) https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 26/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online The ‘starred word’ is formed by incrementally constructing the value of the variable star_word. star_word is initially set to a single-character string, '*'. Then five successive blocks append to the end of this string, one by one, each character of the user’s word followed by a star. Explore the when[a]key_pressed script and make sure you understand this process. To ‘see’ the step-by-step construction of the value of star_word, you could execute it step-by-step or you could temporarily insert say[]for[]secs blocks, starting as shown in Figure 4.39. Figure 4.39 Remove any temporary blocks before continuing. (b) This script contains blocks that are almost duplicates of each other. So, as you may expect, there is a neater way to implement this same task, using a loop. The value of star_word will still be constructed incrementally: in each iteration of the loop, its value will have a character and a star appended to the end of it. There are five repeated blocks (not quite identical, but we will come to that shortly), so a repeat{} loop is a reasonable way to start; amend your script as shown in Figure 4.40. Figure 4.40 We have simply re-used the first of the five almost-identical blocks as the loop contents, which is not quite right of course. Run this script and enter a five-letter word and you will find that the output is simply the first character of your word repeated five times, with stars. In each iteration of the loop contents, the first character from the word is used. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 27/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online What we need is for successive iterations to use different characters, starting with the first and ending with the fifth. This can be done using a version of the technique introduced in Activity 4.6 involving a variable whose value is both used and changed in each iteration. We will use a variable, position, which will be set successively to the positions of the characters within the word, starting with position 1 and moving along one by one to position 5. Each iteration will: use position to access (get hold of) the character at the current position append the character at the current position, and a star, to the value of star_word increase the value of position by 1, ready for the next iteration. The script shown in Figure 4.41 does just this; amend your script accordingly and run it. Each change is circled. Figure 4.41 Maximise Explore the script and make sure you understand how it works. You could again temporarily insert a say[]for[]secs block to enable you to see the incremental construction of the value of star_word, such as in Figure 4.42. Figure 4.42 The way the iterations work might be visualised as shown in Figure 4.43, with an example input 'rover'. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 28/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Figure 4.43 Maximise After the specified five iterations, the value of the variable star_word is fully constructed, ready for display to the user. Notice we don’t need to worry about position ending up set to 6; the loop’s contents are not run a sixth time, so no attempt is made to access the non-existent sixth character of the word. A variable such as position is known as an index variable, so called because it is used to index or provide access to an individual item of data within a collection. Here, the characters within a string are accessed in turn using their successive positions within the string. We say that an index variable enables a program to iterate over a string – that is, to repeatedly step through the string’s characters, processing them one by one. Remove any temporary blocks before continuing. (c) Since the looping block that is used, repeat{}, has input value 5, this script only works with words of five letters. (Try entering words of different lengths to see why.) However, another benefit of using a loop here is that a small amendment enables it to work with strings of any length. Amend your script as shown in Figure 4.44 (the changes are circled) and try it out with words of different lengths. Figure 4.44 Maximise https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 29/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online With length_of[word] as the loop’s input value, the number of iterations is the same as the number of characters in the user’s word. The iterations work just as before, except that they now process all of the characters in the input word, however many there are. (d) Next, suppose a when[b]key_pressed script is required to get a word from the user and display the number of vowels in the word. This is a different sort of specification from the previous one, since the processing involves counting, rather than the construction of a string. But the technique of using an index variable can quite easily be adapted for this sort of task. Recall from Part 3 that a simple way to check whether a given character is one of a set of specific characters is to use a list populated with those specific characters. Then, given a character to check, it can simply be checked for inclusion in the list. Here, we want to check whether a character is a vowel, so as you can see we have created a list VOWELS and a when_green_flag_clicked script that populates VOWELS with the five vowels 'a','e', 'i', 'o' and 'u'. (Although ‘y’ sometimes acts as a vowel (for example, in ‘myth’), we are not including it as one here.) The when[b]key_pressed script will need to access and check each of the characters of the user’s word, counting how many of them are vowels. We will employ an index variable, position, to access each character using its position in the word. Another variable, vowel_count, will keep a count of the vowels found. Again, since each character needs to be accessed, one per iteration, the number of iterations should be the length of the word. The idea might be visualised as shown in Figure 4.45. Figure 4.45 Maximise Now start the script as shown in Figure 4.46. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 30/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Figure 4.46 Over to you Complete the script by inserting loop contents to do the following: if the character at the current position is a vowel, increase the value of vowel_count by 1 increase the value of position by 1. Reveal solution (e) Finally, suppose that a when[c]key_pressed script is required to get a word from the user and tell them the position in the word of the first vowel, or that there are no vowels. So, for example: if the user enters 'Coronation', then they are told 'The first vowel is at position 2' if they enter 'Street', they are told 'The first vowel is at position 4' if they enter 'myth', they are told 'No vowels'. This specification is again slightly different to the previous one as it doesn’t necessarily require iteration over all characters in the word; if the word contains a vowel, then the loop can stop once the first vowel has been found. One way to achieve this is to use a conditional loop in conjunction with an index variable. The loop should iterate over the word, accessing each character using an index variable position, until the character at the current position is a vowel, or position is greater than the length of the word. Once the loop has ended, if position is greater than the length of the word, there are no vowels; otherwise the value of position is the position of the first vowel. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 31/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Over to you Create a when[c]key_pressed script to meet this specification. Reveal solution Note that all that is required in the loop contents is to increase the value of position since the necessary processing (the check for inclusion in VOWELS) is done by the loop condition. Note also that it is important to include, as a component of the loop condition, the check for position exceeding the length of the word. This ensures that the condition reports 'true' at some point, and hence that the loop ends. See what happens if the condition is changed to simply check whether the current character is a vowel, as shown in Figure 4.49. Figure 4.49 Run the script, observing the value of position in its watcher, and enter a word containing no vowels: an infinite loop results and the script executes indefinitely. Click the red stop icon to stop the script. The problem is that, since there are no vowels, the value of position increases beyond the final position in the word. At that point, the block letter[position]of[word] reports the empty string ('') and the loop condition reports 'false', since the empty string is not in VOWELS. Thus the value of position is then continually increased with the condition continually reporting 'false', and so the loop never ends. A completed program is provided in Activity_4.8_completed.sb2. Further discussion Index variables An index variable enables different iterations of a loop’s contents to process different items of data within a collection. Our examples were of index variables being used to access individual characters within strings, but you will see that the idea has wider applicability when we turn to lists in the next section. We tend to use the name position for the index variable, but there’s nothing special about this name; an index variable could be called anything meaningful, for example, index. The basic idea of using an index variable to iterate over a string’s characters one by one is quite easily adaptable with a bit of imagination. For example, a simple adaptation of the technique enables iteration to start at a character further on in the string or finish at a character before the final one. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 32/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Whenever it is required to process characters in a string in some regular, predictable way, a loop in conjunction with an index variable is often the way to proceed. Activity 4.9 (self-assessment) Consider the stack shown in Figure 4.50, but don’t create it unless you are stuck. Note that new_word is initialised to an empty string. Figure 4.50 a. If the user entered 'rover', what value would new_word have when the stack has run? b. Describe in general terms the relationship between the strings held by new_word and by word, once the stack has run. 4.2.3 Conclusion Activity 4.10 (exercise) Open a new project. Create a when[space]key_pressed script to do the following: ask the user to enter a new password if any of the characters of the proposed new password is an '@' character, then tell the user 'Invalid: looks like an email address' otherwise set a variable, password, to the new password tell the user 'Password set'. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 33/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online One strategy is very similar to that in Activity 4.8 part (e), and starts as follows: use an index variable to iterate over the new password until '@' is found or the index variable’s value exceeds the final position in the new password (in which case, all the characters in the password must have been processed without finding an '@'). Reveal comment In this section, you have revised and extended your knowledge of fixed loops. You have also met the concept of an index variable and learned how an index variable may be used in processing strings. 4.3 List processing Strings and lists have much in common. A string is a sequence of characters, each at a numbered positon. A list is a sequence of data items (numbers or strings), again each at a numbered position. You have seen that OUBuild provides some similar blocks for each, for example: there is a block that reports the length of a string, and there is a block that reports the length of a list there is a block that reports the character at a specific position in a string, and there is a block that reports the item at a specific position in a list. It may not surprise you to learn that the techniques introduced in Section 4.2 for iterating over strings can be adapted to work with lists. This is what we turn to in this section. 4.3.1 Text processing with lists In Activity 4.8, you created scripts to perform various kinds of text processing, where the text was held as a single string entered by the user. We expected the text entered by the user to be a single word, but in fact the scripts created would have worked even if entire sentences were entered. For example, if word held the sentence shown in Figure 4.52, then the when[a]key_pressed script that you created to apply a decorative star effect would still do so, as shown in Figure 4.53. Figure 4.52 Figure 4.53 https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 34/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online However, using a single string to store a sentence would make some kinds of processing quite tricky. For example, suppose we wished to count the number of occurrences of a particular word, for example, the word 'to', within the sentence. It would be possible, but the code would be quite complicated as there’s no simple way to distinguish individual words within a single string. Lists provide a more flexible way to store text, with words being held at successive positions, as illustrated in Figure 4.54. This allows individual words to be distinguished by virtue of being held at different positions. Figure 4.54 In Activity 4.11, you will learn how to use lists to store text within a program and then learn how such text may be processed. Activity 4.11 (exploratory) Open the project Activity_4.11.sb2 and save it as Activity_4.11_sol.sb2. Scripts are provided that you will work with in due course. We will suppose that when the program starts, the user should be asked to enter a sentence, for subsequent processing in various ways. (a) The complete when_green_flag_clicked script provided stores a sentence entered by the user in a list. Each word of the sentence is stored as an item in a list, sentence. We will consider the idea behind it and then look at the details of the script. The idea is to use a loop set up so that, in each iteration of the loop contents, the user enters a word and that word is added to sentence using the add[]to[] block. But what sort of loop will work when we don't know how many words the user will want to enter? https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 35/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online One way to do this is with a repeat_until{} block in conjunction with what is known as a sentinel value. This is simply a value used to indicate that the loop should end. If the user enters this value to indicate that they have no more words to enter, the loop stops; the loop continues until the sentinel is entered. The when_green_flag_clicked script provided, shown in Figure 4.55, does this, using the character 'q' as a sentinel value. Figure 4.55 The script starts by: emptying the list sentence giving the user instructions getting the first word from the user. Then repeatedly, until the user enters 'q' (for ‘quit’), it: adds the user’s word to sentence gets the next word (or 'q'). Note that there is no need for an index variable here as we are not iterating over an existing list; words are simply added to the list and take up their positions, without those positions needing to be dealt with explicitly. Make sure you understand how this code works. Run it several times, entering 'q' at different stages, whilst observing the value of word and the contents of sentence. You might find it helpful to visualise how this works with specific inputs as shown in Figure 4.56. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 36/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Figure 4.56 (b) Now let’s turn to some ways in which the sentence entered by the user may be processed. Look at the incomplete when[a]key_pressed script provided. When complete, this script should tell the user the number of times the word ‘nice’ occurs in their sentence – for example, ''nice' occurs 2 time(s) in your sentence'. This task might sound familiar: in Activity 4.8, you created a script that counted the number of vowels in a word. Glance back at Figure 4.47, which shows this script, and Figure 4.45 which illustrates how it works with a sample word. A similar approach can be used in creating the when[a]key_pressed script here. This script should iterate over the list sentence, using an index variable position to step along the list positions, enabling each iteration to process the word at a different position in the list. Each iteration will check whether the current word is 'nice', and a variable nice_count will be used to keep a count of the number of times the word 'nice' has been found. Since each iteration processes a word within the list, the number of iterations should be the number of words in the list, that is, the length of the sentence. Over to you Complete the when[a]key_pressed script by creating the loop contents. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 37/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Use the block shown in Figure 4.57 to access the word to be processed in each iteration. Figure 4.57 Try your script out several times: each time start your program with the green flag, enter a sentence and then press your 'a' key. Reveal solution (c) Look at the incomplete when[b]key_pressed script provided. When complete, the script should tell the user a version of their sentence which has every occurrence of the word ‘nice’ replaced by the word ‘pleasant’. For example, if the user’s sentence is 'nice to see you to see you nice', then the script should display the text 'pleasant to see you to see you pleasant'. The general idea will be similar to that in part (b): the script will iterate over the list sentence, checking whether each word is 'nice'. It will incrementally construct the text to be displayed to the user, word by word. If the current word in sentence is 'nice', then the word 'pleasant' will be included in the text to be displayed; if not, then the current word itself will be included. We need to decide what sort of structure to use to hold the new sentence to be displayed. There are several options. 1. We could change the list sentence, replacing each occurrence of 'nice' by 'pleasant' using the replace[]by[] block, and then use sentence itself in the display. However, sentence would be changed irrevocably if there was an occurrence of 'nice'; the original text entered by the user would not be retained. Losing original data can be problematic – here, for example, the when[a]key_pressed script would no longer work as intended. 2. A variable could hold the text to be displayed as a single string, being incrementally constructed by appending the appropriate word in each iteration. You have used this sort of approach – incrementally constructing a string – several times before. 3. We will demonstrate a new approach here that uses a second list to hold the text to be displayed. Let’s call this new_sentence. Each iteration over the original list sentence will check the item at the current position in sentence: if it is 'nice', then 'pleasant' will be added to new_sentence; if not, then the current item itself will be added to new_sentence. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 38/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Once new_sentence has been populated by iterating over all of the words in sentence, the required display can be achieved by the block shown in Figure 4.59. (A say[]for[]secs block with a list as input produces a display consisting of each list item. If any of the items contains two or more characters, the items will be separated in the display by space characters.) Figure 4.59 Over to you Complete the when[b]key_pressed script so that it works as described in option 3 above by creating: the loop contents a final say[] block. Reveal solution A completed program is provided in Activity_4.11_completed.sb2. Further discussion Looping with lists Lists and similar data structures are important components of programming languages. A list allows a collection of data to be stored together and, as you have just seen, processed together. Loops can be important tools in enabling user input to be stored in lists and also in processing data held in lists. Of course, just as with strings, considerable variation is possible. For example, a list may be iterated over in reverse order by using an index variable whose value decreases. Sentinels The use of a sentinel value to stop loops is an important idea in programming and is particularly useful in handling an unknown number of user inputs. Parallel lists The two lists in Activity 4.11, sentence and new_sentence, form what is known as parallel lists. Parallel lists are lists such that each item in one list is related in some way to the item in the same position in the other list. In the case of sentence and new_sentence, the relationship between the lists is that the items at corresponding positions in sentence and new_sentence are identical, except where an item in sentence is the string 'nice' in which case the corresponding item in new_sentence is the string 'pleasant', as illustrated in Figure 4.61. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 39/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Figure 4.61 Parallel lists provide a way of maintaining a relationship between the items in two collections of data. We will explore this further when we consider numerical processing with lists. Activity 4.12 (self-assessment) Suppose two parallel lists, names and scores, are used in a game to hold the names of each of the players and their corresponding scores in the game. At a particular point in the game, the list contents are as illustrated in Figure 4.62. Figure 4.62 a. What is Tyrone’s score? b. Who has the highest score? 4.3.2 Numerical processing with lists The focus in Activity 4.11 was on lists containing words. Lists also provide a convenient way to store collections of numbers – for example, the scores in a game, as in Figure 4.62. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 40/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Once a list holds a collection of numbers, the numbers can be processed, and looping techniques are often useful. It might be required, for example, to: find the largest number in the list, or the smallest find the mean (average) of the numbers list the numbers in order, from smallest to largest. In the next activity, you will learn about some of these techniques and you will see some more ways in which parallel lists may be used. Activity 4.13 (exploratory) Open the project Activity_4.13.sb2 and save it as Activity_4.13_sol.sb2. Scripts are provided that you will look at in due course. Suppose a program is required to enable the processing of distances walked by each of a group of people participating in a charity fundraising event. For simplicity, we will assume that no two participants have the same name. Specifically, once the data has been entered and stored, we will want to create scripts to do each of the following: given a name entered by the user, tell the user the distance walked by the participant with that name tell the user the total distance walked by the group tell the user the smallest (that is, shortest) distance walked by any participant. The nature of these tasks means that the relationship between the names and the distances must be maintained; we simply wouldn’t be able to carry out the first task, for example, if we weren’t able to associate each name with the corresponding distance. To enable the program to maintain this relationship, we will store names and distances in parallel lists, name_list and distance_list. At any given position, the participant whose name is at that position in name_list will have walked the distance held at that position in distance_list. For simplicity, we will assume that the lists should be emptied as the program starts and that the user is then asked to enter all the names and distances. (a) https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 41/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online The when_green_flag_clicked script provided is incomplete since it deals only with the entry and storage of names. When complete, it should enable the user to enter each name and then the corresponding distance, and it should store both items of data appropriately. Over to you Complete the when_green_flag_clicked script by inserting blocks so that, directly after storing a name in name_list, the script: asks the user how many km this participant walked stores the distance input in distance_list. Reveal solution (b) Now that the user can store the data, let’s turn to how this data might be processed. Look at the incomplete when[a]key_pressed script provided. When complete, this script should: ask the user for a participant’s name tell the user that participant’s distance, in the form 'Chesney walked 21km', for example. For simplicity, we will assume that the user enters a valid name – that is, a name that is in name_list. (It is not hard to create code to handle entry of an invalid name, but that is not what we want to concentrate on here.) The script provided gets a participant’s name and stores it in the variable name. We need now to find the distance associated with this name. We can do this using the fact that the participant’s name and their distance are stored at the same positions in their respective lists. So if we can find the position of the name in name_list, we can then use that position to find the corresponding distance in distance_list. So let’s think first about finding the position of the name in name_list. There are various ways to do this. Since we are assuming that the user enters a valid name, we can use a conditional loop which simply examines every item in name_list, using an index variable position, until the name is found, as shown in Figure 4.64. Create this now and try it out. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 42/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Figure 4.64 Note that the assumption that the user enters a name that is on this list is important here: if the name weren’t on the list, then can you see that an infinite loop would occur? Notice that there is no need for the loop contents to do anything other than increase the value of position, as the necessary processing is done by the loop condition. Once the loop ends, the index variable position holds the position of the given name in name_list. This can then be used to get the corresponding distance from distance_list. Over to you Complete the script by adding blocks to do the following: set the variable distance to the corresponding distance from distance_list tell the user that person’s distance, in the form 'Chesney walked 21km', for example. You may want to use a variable for this, incrementally constructing its value to form the required text to display. Reveal solution (c) Now let’s turn to considering how the distances might be processed. Look at the incomplete when[b]key_pressed script provided. When complete, this script should display the total distance walked by all the participants – for example, 'The total distance is 2005km'. The script must add up all the numbers in the list distance_list. We will consider how this might be achieved. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 43/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Think how you might approach the similar task of adding up a list of numbers written on a piece of paper. You might start with the first number on the list, and then successively add each number, crossing it out as you do so, keeping in your head the total so far – a running total, we might call it. Once you get to the final number in the list, and add it to the total so far, you have the overall total. When implementing this process in code, it turns out to be simpler to start with a total so far of 0, to which is added the first number, then the second, and so on, as shown in Figure 4.66. Figure 4.66 The analogous process in code starts by setting a variable, total_distance, say, to 0, as is done in the incomplete when[b]key_pressed script. The script should then use a loop to iterate over each number on the list using an index variable. In each iteration the value of total_distance should have the number at the current position added to it. So the final value of total_distance, that is, the overall total, is constructed incrementally by successively adding each number in the list. Then, once the loop ends, the total distance can be displayed as required. Over to you Complete the when[b]key_pressed script so that it works as described above, by creating: the loop contents (use the block change[]by[] to add to total_distance the number at the current position) https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 44/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online final block(s) to display the total distance in the form 'The total distance is 2005km', for example. Try it out a few times with different distances in distance_list. (Remember that you can use the list’s watcher to quickly add or remove items.) Reveal solution (d) Look at the incomplete when[c]key_pressed script provided. When complete, this script should display the smallest distance – for example, 'The smallest distance is 6km'. How can the smallest (in other words, the lowest, or minimum) number in a list be found by iterating over the numbers in the list? Think about how you would do this yourself, without a computer, faced with a long list of numbers written down on paper – perhaps over several pages. As illustrated in Figure 4.69, you might work your way down the list, starting at the beginning, always keeping in mind the smallest number you have found so far. Whenever you come across a number that is smaller than the smallest number so far, you revise your notion of the smallest number: the smaller number that you have just found becomes your smallest number so far. Once you get to the end, you can be confident that, having considered all numbers in the list, you have found the smallest number. Figure 4.69 https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 45/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Based on this idea, the smallest distance in distance_list can be found using the following strategy: Set a variable, smallest_distance, say, to the first number in the list, as is done in the incomplete script. Compare the second number in the list with the value of smallest_distance; if the second number is less than the value of smallest_distance, set smallest_distance to the second number. Compare the third number in the list with the value of smallest_distance; if the third number is less than the value of smallest_distance, set smallest_distance to the third number. Continue in this manner to the end of the list. To do this, the code will use a loop and an index variable. In each iteration, the number at the current position in the list will be compared with the value of smallest_distance. If it is less than the value of smallest_distance, then smallest_distance will be set to this number. Note that the iterations – the repeated comparisons – should start at the second number in the list, and to get from there to the final number in the list, there must be n – 1 iterations, where n is the length of the list. Over to you Complete the script provided so that that it works as described above, by creating: a block as input to the loop the loop contents final block(s) to display the smallest distance in the form 'The smallest distance is 6km', for example. Reveal solution Notice that, in contrast to the calculation of the total of all list items, where we could initially set the running total to 0, the only appropriate value to initialise smallest_distance to is one of the numbers in the list, and it is simplest to use the first one. Think about what problem could arise if we initialised smallest_distance to 0, for example. A completed program is provided in Activity_4.13_completed.sb2. Further discussion List techniques https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 46/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online The idea of iterating over a list using an index variable is fundamental to processing data in lists, and can be applied in many circumstances. In Activity 4.13, for example, you saw the following examples of this: adding up list items finding the smallest item in a list. The precise technique in each case was inspired by how a human, without the aid of a computer, might mentally process the items in a list. Whenever you are faced with implementing a new way to process a list, think how you might mentally ‘iterate’ over items if performing the task in your head and try to use this to inspire your program. Lists as databases In OUBuild, lists enable the user to maintain simple databases. Parallel lists enable relationships between collections of data to be maintained, also. You have seen two ways of entering data into lists: using blocks, for example, add[]to[] editing the list watcher. There is a third way which enables larger collections of data to be entered more efficiently into a list, which Activity 4.14 introduces. 4.3.3 Conclusion Activity 4.14 (exercise) Open a new project and save it as Activity_4.14_sol.sb2. In this activity, you are going to work with a list of daily temperatures, measured in degrees Celsius, taken over successive days in a month. (a) Create a list, celsius_list. It would be quite possible to create a script to enable the user to enter temperature data into this list, or they might edit the list’s watcher, but there is another way to enter data into a list which is useful – for example, when working with large collections of pre-existing data. Right-click on the list’s watcher and you will see that you are presented with options to import and export the list’s contents, as shown in Figure 4.71. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 47/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online Figure 4.71 Select ‘import’ and navigate to the text file celsius_temperatures.txt that we have provided in the Part 4 folder, which contains the temperature data. Simply select the file, click ‘Open’ and you will see that celsius_list is populated with the temperature data as shown in Figure 4.72. Figure 4.72 The reverse process is also possible, that is, a list’s contents can be stored in a.txt file using the ‘export’ option. (b) A when[space]key_pressed script is required that displays a list of the corresponding temperatures in Fahrenheit. To convert from a temperature in Celsius to one in Fahrenheit, you multiply by 1.8 and then add 32. So the formula for converting a temperature, c, in degrees Celsius to the equivalent, f, in degrees Fahrenheit is f = 1.8 × c + 32. Create another list, fahrenheit_list, and ensure its watcher is visible. Create a when[space]key_pressed script to do the following: empty fahrenheit_list populate fahrenheit_list with the Fahrenheit temperature equivalents, each rounded to the nearest whole number, of the items in celsius_list. https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 48/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online (We will assume that the visible list watcher provides an appropriate display; no further output is required.) You should ensure that: the two lists are parallel so that the item at any position in fahrenheit_list is the Fahrenheit equivalent of the item at the corresponding position in celsius_list your script will work however many items are in celsius_list. (c) Try the effect of running your program more quickly, by selecting the ‘Turbo mode’ option in the ‘Edit’ menu. With lots of items in a list, processing can be noticeably quicker with Turbo mode. Reveal comment In this section, you have learned how lists may be used to store text and numbers within a program, and how such lists may be processed using loops. You have also been introduced to the concept of parallel lists. 4.4 Problem-solving with loops In preceding sections of this part, you have worked with scripts that include loops implementing repetition. In this section, we move on to solving problems using repetition. We will consider how to recognise from a specification that repetition is needed; and then how to progress to implementing and testing a program. Sometimes the need for repetition is reasonably clear from a specification, but sometimes – for example, in the case of checking whether a user’s input data contains a space character – it may be less so. Even when repetition is clearly involved, deciding what kind of loop is appropriate and just how to use it can require some thought. In this section, there are: some short videos to watch, in which a module-team member discusses solving a problem involving repetition a written worked example of problem-solving using repetition a practice exercise for you to do and discuss in a forum. You might find it helpful throughout to refer to the Problem-solving checklist. 4.4.1 Problem-solving in action Designing an algorithm, implementing a program What clues are there in a program specification that tell us that a program may need to repeat something? https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 49/69 17/01/2025, 01:38 Block 2 Part 4 Loops: View as single page | OU online As we did for selection, we can look for tell-tale words. For repetition, these are words such as ‘for each’, ‘how many’, ‘every’, ‘until’, ‘total’, ‘while’, etc. These tell-tales may appear on their own or in combination, such as in the following sentences. For each child whose name is in the list, get the age and address of the child from the user. Check the password to see how many times the space character is included. Add the numbers together until the total exceeds 100. Play the music while the game is on. These sentences can be reworded to use terms such as ‘Repeat (…) times…’or ‘Repeat until (…) …’, or ‘Repeat forever…’ which are similar to the OUBuild programming structures for repetition. These are the sorts of term that can be helpful to use in creating algorithms. We could re-express the sentences above to use such terms and thus give a clearer steer to repetition in an algorithm, as below. The indentation helps identify the actions that are to be repeated. Repeat (length of list) times Input the age of the child with the current name Input the address of the child with the current name Repeat (length of password) times If the current item is the space character, then add 1 to the count Repeat until (the running total is at least 100) Add the current number to the running total Repeat forever Play the music Sometimes, however, the specification lacks such clues, and we might then use our programming experience to decide whether repetition is appropriate. For example, given the requirement of a program to ‘Check that the word does not contain a space character’, we might think about prior experience of https://learn2.open.ac.uk/mod/oucontent/view.php?id=2362922&printable=1 50/69 17/01/2025, 01:38

Use Quizgecko on...
Browser
Browser