Page 45 - Programming the Raspberry Pi Getting Started with Python
P. 45
The function starts with the keyword def. This is followed by the name of the function, which
follows the same naming conventions as variables. After that come the parameters inside parentheses
and separated by commas if there are more than one. The first line must end with a colon.
Inside the function, we are using a new variable called polite_sentence that takes the parameter
passed into the function and adds “ please” to it (including the leading space). This variable can only
be used from inside the function.
The last line of the function is a return command. This specifies what value the function should
give back to the code that called it. This is just like trigonometric functions such as sin, where you
pass in an angle and get back a number. In this case, what is returned is the value in the variable
polite_sentence.
To use the function, we just specify its name and supply it with the appropriate arguments. A return
value is not mandatory, and some functions will just do something rather than calculate something.
For example, we could write a rather pointless function that prints “Hello” a specified number of
times:
This covers the basics of what we will need to do to write our game of Hangman. Although you’ll
need to learn some other things, we can come back to these later.
Hangman
Hangman is a word-guessing game, usually played with pen and paper. One player chooses a word and
draws a dash for each letter of the word, and the other player has to guess the word. They guess a letter
at a time. If the letter guessed is not in the word, they lose a life and part of the hangman’s scaffold is
drawn. If the letter is in the word, all occurrences of the letter are shown by replacing the dashes with
the letters.
We are going to let Python think of a word and we will have to guess what it is. Rather than draw a
scaffold, Python is just going to tell us how many lives we have left.
You are going to start with how to give Python a list of words to chose from. This sounds like a job
for a list of strings:
The next thing the program needs to do is to pick one of those words at random. We can write a
function that does that and test it on its own: