Hardware Reference
In-Depth Information
4. Finally, press the Enter key on the keyboard twice, and the Python Shell recog-
nises that you have finished typing in indented statements.
5. Now ask the Python Shell to run this function by typing in its name with brack-
ets after it:
myname()
6. Try typing myname() a few more times and see what happens.
At first it might seem a little strange that you typed instructions into the Python Shell
but nothing happened. Normally when you type at the Python Shell, things happen as
soon as you press the Enter key, so why didn't it work this time? This time, you did
something different, however: you “defined” a new function called myname and asked
Python to remember the three print statements as belonging to that function.
Python has stored those print statements in the computer memory, rather than run-
ning them straight away. Now, whenever you type myname() it runs those stored
statements, and you get your three lines of text printed on the screen.
Functions are very powerful, and allow you to associate any number of Python pro-
gram statements to a simple name, a little bit like a mini-program. Whenever you want
those program statements to run, you just type the name of the function.
Let's put this to good use by defining a function that draws your house. Then, when-
ever you want a house made from cobblestone, all you have to do is type House() and
it is built automatically for you!
1. So that you don't break your already working buildHouse.py , choose
File Save As from the editor menu, and call the new file buildHouse2.py .
2. At the top of the program after the import statements, define a new function
called house :
def house():
3. Now move the midx , midy , and all of your setBlocks() statements so that
they are indented under the def house(): line. Here is what your program
should now look like. Be careful to get the indents correct:
import mcpi.minecraft as minecraft
import mcpi.block as block
mc = minecraft.Minecraft.create()
SIZE = 20
def house():
midx = x + SIZE/2
midy = y + SIZE/2
 
Search WWH ::




Custom Search