If you recall the lesson on colors, you'll remember that we ended up creating a big block of mostly repetitive code. There is a better way to accomplish what we did there and that's using loops. This lesson will be a brief introduction to loops, but future lessons will build upon it and teach you how to write the color palette program without much repetition.
Let's start with a simple form of looping: while
loops. Take a look at the
following example:
The following diagram explains how that bit of code works:
As you can see from the diagram, the program starts with a variable n
that has
been initialized to 0
. We start the loop by checking the value of n
.
Everything inside the while
loop is indented once (has the same amount of
whitespace before it). The contents of the loop are usually called the "body" of
the loop. The body of this loop makes sure that n
is incremented by 1
. The
body also has a "side-effect" of printing the value of n
. And that's how we
end up with 5 print statements. When n
finally becomes 5
, it no longer
passes the n < 5
check and the loop exits. Finally, the last line of the
program runs as expected.
Note that we start looping at n = 0
and never print out n
as 5
. This is a
very common pattern in computer science (starting at 0
). This will be an
especially important pattern in Code the blocks, since the 3D plane we're
operating in is centered around the coordinates 0, 0, 0
.
The source-pane below has been populated with a partial example that combines inputs with the loops that you just learnt about. The purpose of this piece of code is to accept a number from the user between 0 and 10 and place that many cubes. See if you can finish the piece of code.
You'll notice things like int()
and str()
in the code. Don't worry about
them for now. We'll go over "types" in a future lesson.
In the next lesson, I'll reveal the solution and go over it.
© 2024 Abhin Chhabra | Sitemap