Hardware Reference
In-Depth Information
The a in this case is called the loop control variable. This means it is the variable
that is used to hold the value of the loop every time it runs the code in the loop
body. The first time it runs, it has the number 0 in it, the second time it has the
number 1 in it, and so on.
The range(10) tells Python that you want it to generate a sequence of ten
numbers from 0 to 9, through which the for loop will count.
The colon ( : ) at the end is just like the colon that you used in earlier adventures
with your while loop and your if statements. The colon marks where the start
of the body code begins. The body code is the code that (in this case) is to be
repeated 10 times.
Any Python statements inside the loop (in other words, the statements that are
indented one level from the for statement) will be able to access the variable
a and this variable will hold a different value each time round the loop.
You can use the loop control variable a anywhere in the program statements
inside the loop body for any purpose. You don't have to call the variable a all the
time. You can think up any name you like for it, and it is good practice to think up
variable names that are more descriptive, so that others who read your program
can more easily understand it. A better name here for the variable instead of a
would be count or number_of_times .
Building a Huge Tower with.a for.Loop
How would you like to build an enormous tower out of blocks inside the Minecraft
world? Now that you know all about for loops, you can. Just follow these steps:
1. Start writing a new program by choosing File New File from the menu. Choose
File Save As from the menu, and name it tower.py .
2. As usual, import the modules you need:
import mcpi.minecraft as minecraft
import mcpi.block as block
3. Connect to the Minecraft game:
mc = minecraft.Minecraft.create()
4. If you build your tower where your player is standing it will be easier to find, so
your first job is to identify the position of your player by typing:
pos = mc.player.getTilePos()
 
Search WWH ::




Custom Search