Hardware Reference
In-Depth Information
Note that the body of the code is indented. his 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.
Now enter the following to call the function you just deined:
printHelloUser(“Fred”)
You're now ready to use what you've learned in this chapter to write a printInsult func-
tion. To begin, enter the following code in an interactive Python window, remembering the
indentation:
from random import choice
def printInsult (username, age):
adjectives = [“wet”, “big”]
nouns = [“turnip”, “dog”]
if (age < 16):
ageAdjective = “young “
else:
ageAdjective = “old “
print (username + “, you are a “ +
ageAdjective + choice(adjectives) +
“ “ + choice(nouns))
Now, whenever you need a personalised insult you can just call printInsult , with your
victim's name and their age, and it will produce one on demand! So, to insult 10-year-old
Fred, you would write the following code line:
printInsult(“Fred”,10)
And Python would print something like this:
Fred, you are a young wet turnip
 
Search WWH ::




Custom Search