您在這裡

Definitions and uses

2 九月, 2015 - 17:59

Pulling together the code fragments from the previous section, the whole program looks like this:

def print_lyrics():
    print "I'm a lumberjack, and I'm okay."
    print "I sleep all night and I work all day."

def repeat_lyrics():
    print_lyrics()
    print_lyrics()

repeat_lyrics()

This program contains two function definitions: print_lyrics and repeat_lyrics. Function definitions get executed just like other statements, but the effect is to create function objects. The statements inside the function do not get executed until the function is called, and the function definition generates no output.

As you might expect, you have to create a function before you can execute it. In other words, the function definition has to be executed before the first time it is called.

Exercise 3.1. Move the last line of this program to the top, so the function call appears before the denitions. Run the program and see what error message you get.

Exercise 3.2. Move the function call back to the bottom and move the denition of print_lyricsafter the definition of repeat_lyrics.. What happens when you run this program?