Hardware Reference
In-Depth Information
Using Python Functions
One of the things you might want to do later is build a whole town with houses of
many different designs. The program for a whole town could become quite big and
complex, but fortunately there is feature inside the Python programming language
that helps you package up that complexity into little chunks of reusable program code.
It is called a function .
With a Python function you can group related Python program statements and
give them a name. Whenever you want to run those program statements as a
group, you just use the name of the function with brackets after it.
You might not realise it, but you have been using functions all the way through
this topic, ever since you posted a message to the Minecraft chat with mc.
postToChat("hello") in the very first adventure. postToChat() is
a function, which is just a group of related program statements that get run
whenever you use the word postToChat() inside your program.
Before you change your working buildHouse.py program to use a function for the
house, try out some functions at the Python Shell to make sure you understand the
idea:
1. Click on the Python Shell window to bring it to the front.
2. Type the following into the Shell window, which will define a new function called
myname :
def myname():
he def means “define a new function and here is its name”. Just like earlier
with the while , if and for statements, you must put a colon (:) at the end of
the line so that Python knows to expect you to provide other program state-
ments as part of the body of this function.
3. The Python Shell automatically indents the next line for you, so that Python
knows they are part of the function. Type in a few lines of print statements
that print your name and information about yourself. Don't be surprised that
nothing happens as you type in each line; that is correct. Be patient, all will
become clear in a moment!
print("my name is David")
print("I am a computer programmer")
print("I love Minecraft programming")
 
 
Search WWH ::




Custom Search