Page 241 - Learn To Program With Scratch
P. 241
Figure 9-9: Using the contains block to check whether a string is
in a list
Bounds Checking
The four list blocks (delete, insert, replace, and item of) require an
input parameter that specifies the index of the item you want to access.
For example, to delete the seventh element of our dayList, we use delete 7
of dayList. But what do you think will happen if you use an invalid index
with one of these blocks? For example, how would Scratch respond if you
asked it to delete the eighth element of our dayList (which only contains
seven elements)?
Trying to access an element past the boundaries of a list is, technically,
an error. Rather than display an error message or abruptly terminate your
program, however, Scratch silently tries to do something sensible with the
offending block. For this reason, the absence of error messages does not nec-
essarily mean the absence of errors. Problems may still exist in your code, and
when they do, you still need to fix them. Scratch won’t complain about invalid
indexes in your blocks, but the outcome usually won’t be what you intended.
Table 9-1 shows what can happen when you try to access dayList using an out-
of-range index.
Table 9-1: Unexpected Results from Bad List Indexes
Command or Function Block Result
Returns an empty string because dayList has only seven items .
The same thing happens if you use an index less than 1 .
Scratch ignores the .9 and returns the first item of dayList, which is
“Sunday” . Similarly, if you asked for item 5 .3, Scratch would return
the fifth item, “Thursday” .
Scratch ignores this command because it attempts to create a gap
in the list . The list remains unchanged .
This has the same effect as the add command . It adds “Newday”
to the end of the list .
The command is ignored (because dayList has only seven elements),
and the list remains unchanged .
Lists 219
www.it-ebooks.info

