Chapter 10

Getting Loopy

IN THIS CHAPTER

check Using different kinds of loops

check Nesting loops

check Coding the Fibonacci Sequence

Loops are a type of control command that are common to every programming language. Computers are really good at repeating the same action over and over again, which is great because as humans, that can get really boring!

Loops can be useful for a variety of purposes. You could animate a cloud in a video game to move from the left of the stage to the right and back to the left and repeat that throughout the entire game. Or you may want to compute how much money you would have after one year if you invest an initial quantity into a bank account that accrues compound interest. Consider placing $100 into that account, with a daily interest rate of 1%! Day 1 you would have $100, day two you would have the balance * 1.01, which would be $101.00, day three you would have the balance * 1.01, which would be $102.01, and so on. If you loop through the process of computing balance = balance * 1.01 for 365 iterations, you would have $3,778.34 at the end of the year! It would be a pretty long program if you had to write balance = balance * 1.01 over and over, 365 times, without using a loop!

Loops, Unplugged

You and your young coder can explore loops in many ways in the physical world. Loops repeat actions until a certain condition is met; for example “Take a bite of food until your plate is clean.” A condition for a loop can also be very specific with how many times it repeats, for example “Take one step until you have taken ten steps” would be a loop that you know repeats exactly ten times. But with code, you can also get tricky and have a loop that says “Take two steps until you have taken ten steps,” which would actually only repeat the action “take two steps” five times instead of ten! Either way, loops always have a condition and a set of actions that will repeat until the condition is met.

Repeat fun, unplugged

A really fun and easy way to introduce your young coder to loops and repeating actions is to throw a dance party! Identify five dance moves: clap, stomp, wiggle, jump, and squat. Then write a series of moves on one line on the white board (or even a piece of paper):

Repeat 2 times:

Clap, clap, clap

Repeat 3 times:

Stomp, stomp, clap

Wiggle, jump, squat, jump

Clap

The entire dance would consist of 33 actions in total, but you only have to write 11! You can even have your young coders write their own dances using the same actions!

Random loop conditions, unplugged

One fun way to get your coder understanding how the conditions and actions of loops work is to pass out a sheet with a number line on it from 1 to 18 and give each person a die. In teams of two, have each person roll the die five times. The first number that they roll is the starting position on the number line, the next three numbers they roll are added together and is the ending position on the number line, and the fifth number that they roll is the increment value that they use as their action. Code.org offers a really great worksheet for this activity as part of its For Loop Fun puzzle found at https://studio.code.org/s/course4/stage/8/puzzle/1.

Figure 10-1 shows an example of two players playing one round of the game. Player 1 rolled a 3, then rolled three numbers that added to 12 (maybe 5, 6, and 1), then rolled a 4. So she started at 3, ended at 12, and added each 4th number, totaling 21 points!

image

FIGURE 10-1: A sample of the number line unplugged activity from Code.org.

Loop Types and Structures

Most programming languages have two main types of loops: while and for. While loops are also called conditional loops because they’re based on a condition where you won’t typically know how many times the actions repeat. For example, “Take a bite of food until your plate is empty” would most likely be written as a while loop because depending on how big the bites are, you might have to take 10 bites or 20! For loops are also called “counted loops” because they are based on an exact number of times you want something to repeat. For example, “Take one step until you have taken 10 steps” would most likely be written as a for loop because you take exactly 10 steps.

Programming languages also have another type of while loop: do-while. The difference between a while and do-while loop is simply when the condition gets checked. In a while loop, the computer checks the condition first, then performs the action if the condition is true. For example, “Take a bite of food until your plate is empty” in a while loop would first check to see whether the plate is empty; if it isn’t empty then you take a bite. This can be a good idea, because if your plate is already empty then it doesn’t make sense to take a bite. In a do-while loop, the computer checks the condition after the action has been performed at least once. For example, “Take a bite of food until your plate is empty” in a do-while loop you take a bite no matter what, and then check to see whether the plate is empty. This probably makes more sense in this context, because it isn’t likely that you were given an empty plate.

For loops also have two types. A typical for loop has a starting point, a condition, and an increment amount (similar to the Random Loop Conditions unplugged activity shown earlier in this chapter). Oftentimes, for loops have a starting number, a condition which specifies when the loop should stop iterating, and a number by which you should increment for each iteration of the loop. For example, you have 10 baskets and want to put an egg in all of the even-numbered baskets. The starting number would be 2, the condition for when the loop should stop would be when you have reached 10 baskets, and the number by which you should increment is 2. Then you would put an egg in baskets 2, 4, 6, 8, and 10. Another type of for loop is called the for-each loop. A for-each loop simply iterates through all the items in a list. (Chapter 11 goes into more detail about lists.) This can be very useful if you want to perform the same action for every item. For example, “Give each of your classmates a high five” would best be represented as a for-each loop; for each classmate, give him a high five.

Infinite loops

Something that often trips up young coders is infinite loops. An infinite loop is any type of loop that never stops repeating. This can happen pretty easily if you set your conditions incorrectly. For example, if your young coder is 8 years old and you have a while loop that says “while you are older than 7 years old, do a jumping jack,” then your young coder has to do jumping jacks FOREVER!

Infinite loops often make your program either look like it’s not doing anything, or just crash. In Chapter 13 you can find out how to debug infinite loops.

remember You can also create a specific form on an infinite loop on purpose, for instance, coding a forever loop in Scratch to play background music that loops the entire time a game is being played. To break an infinite loop, you might need to use an if-then statement such as “if the player loses all lives in frogger, then stop all.” (See Chapter 2 for a description of these conditional statements.)

Actions repeated in loops

The last thing to know about all loop types is that you can have as many actions as you want in the loop. It could just be one action — “take a bite” — that you have to repeat, but it could also be eight actions — for example, if you're wrapping a lot of gifts, your actions to repeat might be “grab a gift from the unwrapped pile of gifts, take the price tag off the gift, measure the quantity of wrapping paper, cut the paper to the right measurements, fold the paper around the gift, tape the paper closed, write a message on the gift, place in the pile of wrapped gifts.”

Conditions of loops

As you might have noticed already, the conditions of loops are always of Boolean type. Chapter 7 introduces you to Boolean types if you need a refresher, but simply speaking a Boolean gives two choices: true or false. The condition of a loop always evaluates to either true or false, to know if the action(s) inside the loop repeats again, or the loop ends and the rest of the program continues.

Using pseudocode

Most programming languages have the same general structure for while loops, do-while loops, and for loops. Loops are written with indentation to make it clear which actions are a part of the repetition, and which actions simply come after the loop.

  • While loops:

    while(condition)

    action1

    action2

    END_WHILE

  • Examples:

    while(sunIsUp)

    playOutside

    END_WHILE

    while(rightArrowKeyIsPressed)

    moveRightOneStep

    END_WHILE

  • Do-while loops:

    do

    action1

    action2

    while(condition)

  • Examples:

    amount = 0

    do

    amount = amount + 5

    while(amount < 50)

    do

    takeBiteOfFood

    while(plateHasFood)

  • For loops:

    for(starting_bound; condition; increment)

    action1

    action2

    END_FOR

  • Examples:

    balance = 0

    for(days = 1; days <= 365; days++)

    balance = balance * 1.01

    END_FOR

    for(walls = 1; walls <= 4; walls++)

    walkForwardLengthOfWall

    turnRight(90degrees)

    END_FOR

  • For-each loop:

    for(item in list)

    action1

    action2

    END_FOR_EACH

  • Examples:

    for(classmate in class)

    highFive

    END_FOR_EACH

    totalScore = 0

    for(score in testScores)

    totalScore = totalScore + score

    END_FOR_EACH

  • Explicit infinite loop:

    while(TRUE)

    action1

    action2

    if(condition)

    BREAK_LOOP

    END_WHILE

  • Examples:

    while(TRUE)

    exploreCave

    if(flashlightDies)

    BREAK_LOOP

    END_WHILE

    while(TRUE)

    number = askUserForNumber

    if(number is 5)

    BREAK_LOOP

    END_WHILE

remember An expression such as points++ means points = points + 1. Similarly, countdown-- means countdown = countdown - 1.

Using Scratch

Scratch offers three different type of loops, all shown in Figure 10-2, found under the Control category. The repeat loop is just like a for loop; it repeats exactly the number of times specified by the coder. The forever loop is one that is unique to Scratch; it repeats until the user presses the red stop sign, or uses a Stop block. It's basically a deliberate infinite loop! The repeat-until loop is just like a while loop; it repeats until the condition that the coder specifies is reached.

image

FIGURE 10-2: Scratch provides three different types of loops.

warning A typical while loop continues repeating the actions while the condition is true, and stops when the condition becomes false. In Scratch, the repeat-until loop continues repeating the actions while the condition is false, and stops when the condition becomes true. This can be really tricky for anyone, but especially young coders who’re switching between Scratch and other programming languages. The best way to mitigate this problem is to read the code in English. For example, the code for a typical while loop might read as “While my plate has food, take a bite”, whereas the code for a Scratch repeat-until loop might be read as “Repeat taking a bite until my plate is empty.” When in doubt, write it out!

Here are some examples of simple Scratch programs you might want to write using each of the types of loops that Scratch offers.

Repeat loop

The program shown in Figure 10-3 shows a repeat loop where you can have your sprite draw a shape on screen. You can change the number of times the loop repeats and the turn angle to create other shapes too. Give it a try!

image

FIGURE 10-3: A simple Scratch program that uses the repeat loop.

Forever loop

The program shown in Figure 10-4 shows a forever loop where the character follows the mouse pointer! So anywhere you move your mouse, the character points towards it and moves 10 steps. Try changing the number of steps that the sprite takes each time to see what happens when you press the green flag!

image

FIGURE 10-4: A simple Scratch program that uses the forever loop.

Repeat-until loop

The program shown in Figure 10-5 shows a repeat-until loop where the character moves forward until it touches the color red. This can be used with random numbers and more than one character to create a race game!

image

FIGURE 10-5: A simple Scratch program that uses the repeat-until loop.

Using Python

Python has two types of loops that it supports: while and for-each. A while loop can be written as a do-while loop however, and a for-each loop can be written to simulate a basic version of the for loop (where you start at one number and increment by one each iteration of the loop).

technicalstuff When you want to use a Python for-each loop like a for loop, use the range function. In this case, range includes the first number and excludes the second number. So if you want to print all the numbers from 1 to 10, your range parameters is range(1, 11).

warning In Python you must make sure that everything is indented properly. This means that any action that is repeated is indented once from the loop. If you have an action that you want to happen when the loop is done iterating, it should not be indented. For example:

while condition

actionToBeRepeated1

actionToBeRepeated2

actionToHappenAfterLoopCompletes

  • While loops:

    while condition:

    action1

    action2

  • Examples:

    count = 1

    while count <= 10:

    print count

    count = count + 1

    number = 0

    while number != 5:

    number = input("Guess the number ")

    print "You guessed the right number"

  • Do-while loops:

    action1

    while condition:

    action1

  • Example:

    number = input("Guess the number ")

    while number != 5:

    number = input("Guess the number ")

    print "You guessed the right number!"

  • For loops:

    for variableName in range(number1, number2):

    action1

    action2

  • Example:

    for count in range(1, 10):

    print count

  • For-each loops:

    for item in list:

    action1

    action2

  • Example:

    classList = ["Sarah", "Camille", "Steve", "Rebecca"]

    for classmate in class:

    print "Hi " + classmate”

    name = "Sarah"

    for letter in name:

    print letter

  • Explicit infinite loop:

    while True

    action1

    action2

    if condition:

    break

  • Example:

    while True:

    password = raw_input("what is the password? ")

    if password == "password":

        break

    print "Congratulations, you now have access"

Nesting Loops

If you played the Repeat Fun unplugged activity at the beginning of this chapter, then you’ve already seen a nested loop! Nested loops are basically a loop within a loop. This can be useful for making drawings like fractals or fun shapes that repeat but slightly change each time, creating ASCII art, or even having complex repetitions. The examples in the following sections show how nesting loops can help create some fun programs. You can nest any kind of loop inside any other kind of loop. For example, you can nest a for loop inside a while loop!

technicalstuff A fractal is a geometric object that has self-similarity — it shows the same pattern whether you’re looking at it far away or close up. Fractals can provide mathematically accurate models of coastlines, mountains, and other real objects from nature. Loops (specifically, recursive loops) are used to code fractals. One of the earliest uses of computer graphics in big-screen movies was the creation of fractal-based scenery for the transformation of the Genesis planet in Star Trek II: The Wrath of Khan. Khhannnnnn!

Using pseudocode

Nesting loops can happen in any combination. Here are some examples of nesting loops, but this list is not exhaustive.

  • For-each loop nested inside a for-each loop:

    for(item in list)

    action1

    for(item in list)

    action2

    action3

    END_FOR_EACH

    action4

    END_FOR_EACH

  • Example:

    jellyBeanCount = 0

    for(jar in jars)

    for(jellybean in jar)

    jellyBeanCount = jellyBeanCount + 1

    END_FOR_EACH

    END_FOR_EACH

  • While loop nested inside a for-each loop:

    for(item in list)

    action1

    while(condition)

    action2

    action3

    END_WHILE

    action4

    END_FOR_EACH

  • Example:

    for(room in house)

    while(wallsWhite)

    paintWallsBlue

    END_WHILE

    END_FOR_EACH

Using Scratch

Nesting loops in Scratch can be a lot of fun when you introduce the pen and start drawing fun shapes. Here are some basic examples of nesting loops in Scratch.

Repeat loop nested inside a repeat loop

Figure 10-6 shows an example of a Scratch program that draws 10 concentric squares. The outer repeat loop is responsible for repeating 10 times for each square. The inner repeat loop is responsible for repeating 4 times, for each line and turn in each square.

image

FIGURE 10-6: A Scratch program that nests a repeat loop inside another repeat loop.

Repeat loop nested inside a repeat-until loop

Figure 10-7 shows an example of a Scratch program that draws squares in random places around the screen until the user presses the space key.

image

FIGURE 10-7: A Scratch program that nests a repeat loop inside a repeat-until loop.

Using Python

One of the most fun programs to write in Python with nested loops is ASCII art. In coding, each character and symbol that you can type on a keyboard has a number representation called its ASCII number. Although in today’s programming languages, you can type the character or symbol in your program, in the past you would have to use the ASCII number representation. ASCII art is basically when you create a picture using characters or symbols. There are some pretty amazing ASCII art examples, such as the one in Figure 10-8. As a kid, Camille used to have ASCII portraits of all the Star Trek: The Original Series cast members on her wall!

image

FIGURE 10-8: An example of an ASCII art picture showing a lion from Wikipedia.

You can create a simple ASCII art program in Python using nested loops! For example, to create this pattern:

#

##

###

####

#####

######

#######

########

#########

The algorithm might be:

Print 1 # on Row 1

Print 2 # on Row 2

Print 3 # on Row 3

You could represent this using nested loops too!

for row in range(1, 11):

        rowText = ''

        for column in range(1, row):

                rowText = rowText + '#'

        print rowText

Coding the Classic Fibonacci Sequence

A fun program to write with your young coder that uses loops is to create the Fibonacci Sequence. The Fibonacci Sequence is a series of numbers that appears in art and nature, including the proportions of the Mona Lisa and the spirals of a nautilus shell. As a reminder, the Fibonacci Sequence is represented as:

Fn = Fn-1 + Fn-2

Where

F0 = 0

F1 = 1

In other words, start with the first two numbers as 0 and 1. The next number is the sum of the two numbers preceding it. So the first ten numbers of the sequence would be:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34

To write this in Python, your code for printing the Fibonacci Sequence would be:

first = 0

second = 1

sequence = str(first) + ", " + str(second)

numberOfNumbers = input("How many numbers do you want to print? ")

for index in range(0, numberOfNumbers):

next = first + second

first = second

second = next

sequence = str(sequence) + ", " + str(next)

print sequence

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.144.170