August 31, 2015 2 Comments
In these posts I outline the contents of each project in my book Python For Kids For Dummies. If you have questions or comments about the project listed in the title post them here. Any improvements will also be listed here.
What’s in Project 5
Project 5 introduces functions by revisiting the Guessing Game from Project 3 and recasting it using a function. The project covers the def keyword, calling a function, the fact that a function must be defined before it can be called. The project also covers how to communicate with a function (both sending information to it by passing parameters and getting information from it, using the return keyword). In order to define a function, you need to give it a name, so the project sets out naming rules for functions. You should also be documenting your code, so the project introduces docstrings, how to create them, what to put in them and how to use them.
The project illustrates a logical problem in the code an explains what a local variable is. It introduces the concept of constants defined in the body of a program that can be accessed by code within a function. A function which conducts the game round is put inside a while loop. The user interface is changed to allow the user to exit the loop. This involves creating a quit function which first checks with the user to confirm that they want to quit, then using the break keyword to break out of the loop to quit, or the continue keyword if the user aborts the quit. The sys module is introduced in order to use sys.exit.
The name of the project is actually “A More Functional Guessing Game” – named as such since it will be using a function to make the guessing game work better, but some editor somewhere had a humor transplant and changed that title.
The callout on Figure 5-4 should read “The right place for an argument.” They completely ruined that pun <sigh>
The code at the bottom of page 133 should read:
QUIT = -1 QUIT_TEXT = 'q' QUIT_MESSAGE = 'Thank you for playing'
That is, an additional constant QUIT_MESSAGE = ‘Thank you for playing’ should be at the bottom of the page.
The line avg = str(total_guesses/float(total_rounds)) in step 4 on page 135 should be 4 lines down – being the first line in the else: block. Otherwise the logic does not work properly when you quit in the first round. The corrected code reads:
# new if condition (and code block) to test against quit if this_round == QUIT: total_rounds = total_rounds - 1 # removed line from here if total_rounds == 0: stats_message = 'You completed no rounds. '+\ 'Please try again later.' else: avg = str(total_guesses/float(total_rounds)) # to here stats_message = 'You played ' + str(total_rounds) +\ ' rounds, with an average of '+\ str(avg) break
This same correction needs to be made to the “Complete Code” on page 138.