Page 47 - Programming the Raspberry Pi Getting Started with Python
P. 47

it is a new variable local to the function. The stub then reduces the lives remaining by 1 and returns
          False to indicate that the user has not won yet. Eventually, we will put in checks to see if the player
          has guessed all the letters or the whole word.
             Open the file 4_5_hangman_play.py and run it. You will get a result similar to this:



             What happened here is that we have whizzed through all 14 guesses very quickly, and Python has
          told us what the word was and that we have lost.

             All  we  need  to  do  to  complete  the  program  is  to  replace  the  stub  functions  with  real  functions,
          starting with get_guess, shown here:









             The  first  thing get_guess does is to tell the player the current state of their efforts at guessing
          (something like “c--c--n”) using the function print_word. This is going to be another stub function
          for now. The player is then told how many lives they have left. Note that because we want to append a
          number  (lives_remaining)  after  the  string Lives  Remaining:,  the  number  variable  must  be
          converted into a string using the built-in str function.
             The  built-in  function input  prints  the  message  in  its  parameter  as  a  prompt  and  then  returns
          anything  that  the  user  types. Note  that  in  Python  2,  the input  function  was  called raw_input.
          Therefore, if you decide to use Python 2, change this function to raw_input.
             Finally, the get_guess function returns whatever the user has typed.
             The stub function print_word just reminds us that we have something else to write later:




             Open the file 4_6_hangman_get_guess.py and run it. You will get a result similar to this:

















             Enter guesses until all your lives are gone to verify that you get the “losing” message.
             Next, we can create the proper version of print_word. This function needs to display something

          like “c--c--n,” so it needs to know which letters the player has guessed and which they haven’t. To
          do this, it uses a new global variable (this time a string) that contains all the guessed letters. Every
          time a letter is guessed, it gets added to this string:

             Here is the function itself:
   42   43   44   45   46   47   48   49   50   51   52