For Loops Guide

Yolanda Shen

Supplements the list portion of Lists and Scoping

Corresponds with Lists Lab 

This guide assumes you:

Goals

Outline

  1. Motivating Example (how to read errors)
  2. For Loop Overview: for i vs for each item
  3. How the For Loops Relate
  4. Summary


1. For Loop Overview

These are the two most widely used for-loops in iteration:

                        

for i Loop

Let’s say we have the following script:

Here, i iterates over the numbers in the range 1-10, inclusive. In other words,

On the first loop, i = 1 and the sprite would say “1” for two seconds;

Second loop: i = 2 and the sprite says “2”;

...so on until the tenth loop.

for each item Loop

Here, item iterates over the items in the list. On the first loop, item = a so the sprite would say a, and this would continue until we reach the end of the list.

Q: Now what if we wanted to ‘say’ the positions (aka index) of a list like ? Which for-loop would we use?

A: We’d want to use the for i  loop, even though we are dealing with a list, because it keeps track of the numerical placements (1, 2, 3). On the other hand, for each item does not keep track of the index, so you don’t know where you are in the list.

for each item has “blinders”

Another way of thinking about for each item is to envision that it has blinders. Let's take a look at the image below.

 …

for each item may be able to point at the actual contents of the list, but since it has blinders on, it can’t ‘look around’ to figure out its index. The only way for us to know where in the list we are is to use for i .

2. How For Loops Relate

Making Our Own for each item Loop

        

        

Say we didn’t have a for each item loop and wanted to make our own. Let’s consider what we might put in the ? in order to achieve the same behavior.

A: 

Yay! We’re allowed to do this because once we know the position of an item in the list,

Snap! has a handy block that allows us to immediately access the item.

Making Our Own for i Loop

Let’s try the other way around now.

A:

 

Unfortunately, this block can be a little buggy. Here is why:

If we know item = a , and  list =  , there is no way even we humans could know which “a” is being referred to! The  picks the first index available. With the given list of all ‘a’s, the block will report 1.

*Note: There are a few somewhat complex ways to go from for each item  for i, but using for i + is simpler and accomplishes the same thing.

3. Summary

For Loops

for i  for each item

In terms of how the for loops are related, you can easily convert from for i for each item.

This is useful because you have simultaneous access to the index and the item when using for i and .

You can also convert for each item for i  with the  block, with a limitation.

*Note: There are a few somewhat complex ways to go from for each item  for i, but using

for i +  is simpler and accomplishes the same thing.