Alpha-py-4 : Variations on Sedans

Key concept

Our example

Run the program Alpha-py-4-eggs.py in your shell. It should look similar to:

Look at the program Alpha-py-4-eggs.py in your text editor.

Notice how:

Your turn

Open Alpha-py-4-spam.py in your text editor.

Try making some changes in the text editor. How about building a:

Now save your changes, and run the changed program in your shell.

Be creative

Open Alpha-py-3-ham.py (that you worked on in chapter 3) in your text editor.

Make variations to your picture, too. Create re-usable components that can be used again and again. Save it with a new name, such as Alpha-py-4-ham.py

About Functions

A function is a piece of Python program with a name, so that you can refer to it by it's name. Functions are useful when you want to do the same thing several times - you just define a function once (like writing down a recipe) and then use it several times (like making several pies with the same recipe).

They're even more useful when you want to do almost the same thing several times. You can write a function so that some bits of what it does aren't completely specified, and when the function is used the details get filled in (like having a recipe that will make several different kinds of pie).

Functions are useful even if you're only going to use each function once. Although the program won't be shorter, it will be easier to understand.

To define a simple function that does the same thing every time you use it, write something like this:

def bake_a_pie():
    make_the_pastry
    make_the_filling
    cook_the_pie
And to use it, you just say:
bake_a_pie()

To define a function that can do slightly different things every time you use it, write something like this:

def bake_a_pie(fruit):
    make_the_pastry
    make_the_filling(fruit)
    cook_the_pie
And to use it, give it an "argument" that will make a difference to what the function does:
bake_a_pie(peach)
bake_a_pie(cherry)