Hardware Reference
In-Depth Information
DIGGING INTO THE CODE
Let's just pause for a minute, as there is a little bit of magic to do with functions
that hasn't quite been explained properly yet.
You have been using functions since the start of this topic, mc.postToChat()
is a function, as is mc.getTilePos() , they are both part of the Minecraft API.
You have also defined your own functions with def , such as in Adventure 2 you
designed a house() function of your own. But what really is happening when
you use these functions in your code?
I've been cheating a little up until now and saying “now use this function,” but
the proper way to talk about what is happening here is to say that when you put
house() or buildBridge() in your code, you can say that you call your func-
tion. But what really happens?
All the time your Python program is running, the computer remembers which
statement it is working on at any time, a bit like an invisible finger pointing to
the line in the code that is running. Normally, this invisible finger moves down
the page from top to bottom. When you use a loop, this invisible finger jumps
back to the top of the loop and runs down the code again a number of times.
When you call a function, some extra magic is happening behind the scenes.
Python remembers where this invisible finger was (imagine that it sticks a little
coloured tab at that point in the program) and then jumps into your function,
such as your buildBridge() function. When it gets to the end of the build-
Bridge() function, it jumps back to where it left that little coloured sticky note
and continues from there again.
Using functions in your programs is useful for many reasons, two of the most
important ones being:
You can split a large program up into lots of smaller programs.
You can re-use the code inside a function from lots of different
places in the same program.
Both of these reasons will make your programs easier to read and easier to
modify.
When you call a function, Python will remember where it has got to in your
program and temporarily jump into the function at the point you defined it with
def . When the end of the function is reached, Python jumps back to just after
where it was when it jumped into that function.
Search WWH ::




Custom Search