even?
, is hard to miss, but some people don't like it because in English the question mark would go at the end: is (n) even?
. And in any case English questions don't go after the word if
. But don't try too hard to read or write any programming language as if it were English.You know that the code means "if n is even," but programs are much easier to read and debug when the code says what it means, something like
or
.
even? (n)
block.even or odd
(from problem 1) to make it use the
To decide, it needs a predicate that tests the next letter to see if it's a vowel. It should work like this:
There are many ways to create a block like this. Here's one way, started for you.
Complete it, test it, and save it for future use.
true
or false
. Choose the shape when you first define the block.
use indefinite article (noun)
that works like this:You will need to use with two inputs. The block shows a slot for only one input, but you can use the arrows
to increase or decrease the number of inputs.
The solution to problem 1 needs only one if
statement, because all integers are either even or odd. If the boolean expression (n mod 2 = 0
) evaluates to false
, the number is not even, so it must be odd.
The way problem 4 was approached above used several if
statements because it tested for several conditions.
mod
m reports the remainder when n is divided by m. That remainder is 0 only when n is a multiple of m. So, direction
is a multiple of 60°. So, the predicate direction
is 0, 60, 120, 180, 240, or 300.
When the sprite's direction is not a multiple of 60,
reports a number other than 0. For example, if the sprite's direction is 127°,
reports 7.
When the sprite is pointing in direction 90, reports 0.
In how many other directions will the predicate report
true
?
if-else
and repeat until
) control each of these scripts. Construct and analyze them with your pair programmer, experimenting with the conditions until you are sure you can explain exactly how this code does what it does.
direction mod whatever = 0
, you used direction mod whatever = 20
? direction mod 23 = 0
?turn 2 degrees
or turn 7 degrees
instead of turn 1
?
Data types: snap lets you manipulate a variety of data types. You have already used blocks like letter (1) of (world)
to manipulate strings of characters such as "New York" or "Another hour has passed". You have also manipulated numbers.
The next two problems give you a first taste of a new data type, lists, and show how useful lists can be. In Unit 3, you will study lists in depth.
if
statements in vowel?
, you can make a list of vowels and then test to see if a particular letter is in that list. snap makes that a snap!
vowel?
using list
and contains
.vowel?
. With your pair programmer, figure out how each works. Decide which you find clearer.if-else
, not just if
. Problem 4, however, seems to choose alternatives with plain if
. Why does that work? (There's a subtle hint in the shapes of the