Hardware Reference
In-Depth Information
Create a Stream of Insults!
In the next part of this project, you're going to change the program to produce multiple
insults, which is a good example of the use of functions. You're going to define your own
function that you can call whenever you want an insult, and then create a loop that calls the
function multiple times.
Making Your Own Functions
You define functions in Python by writing def (for definition) followed by the name of the
function and the parameters it takes and a colon (:), followed by the body of the function.
As a simple example, enter the following in an interactive Python window to define a simple
function that will print a personalised greeting:
def printHelloUser (username):
print (“Hello “ + username)
Note that the body of the code is indented. This shows that it is still part of the function on
the previous line. Also note that there are no spaces in the function names. Including spaces
would confuse the computer, so programmers separate words by using capitals in the middle
(like printHelloUser in the example). Some programmers call this camel case because the
capital letters in the middle of a word are like humps on the back of a camel.
Python doesn't care what you call your functions, but other programmers will! So if you want
other people to use your code, you should follow conventions.
TIP
Now enter the following to call the function you just defined:
printHelloUser(“Fred”)
You're now ready to use what you've learned in this appendix to write a printInsult func-
tion. To begin, enter the following code in an interactive Python window:
from random import choice
def printInsult (username, age):
adjectives = [“wet”, “big”]
nouns = [“turnip”, “dog”]
if (age < 16):
ageAdjective = “young “
else:
ageAdjective = “old “
continued
 
Search WWH ::




Custom Search