Yesterday was the third day we spent learning the ins and outs of Python. We continue to use Al Sweigart’s book, Invent Your Own Computer Games with Python (available for download here.) The topic of the day was defining functions.
Defining your own functions is one of the most useful skills a coder can have. If you want a program to perform the same task multiple times, simply program that task in a block of code, and give it a name. For example, if I want the computer to ask the user to pick a number several times, I can create a function called pickNumber that the program can call any time it needs it:
def pickNumber(): print('Pick a number between 1 and 10') input() userNumber = input() return userNumber
Python has a huge library of functions that are already defined for programmers. As one of my students who is an accomplished coder said, “Programmers hate reinventing the wheel.”
The game we typed in today involved choosing between two caves, each containing a dragon. One dragon is friendly and will share his treasure. The other is greedy and will eat you up. The girls had to define functions for printing out a descriptive introduction, letting the user choose a cave, randomly picking the bad dragon’s cave and comparing it to the user’s choice, printing the outcome, and asking if user if he or she wants to play again.
The assignment for next class is to write an original game that asks the user to make a choice and output the consequences of that choice.