Section 5.7 Definitions and uses
Pulling together the code fragments from the previous section, the whole program looks like this:
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.
If we move the function call above the definition we will get an error.
Checkpoint 5.7.1.
Q-3: What kind of error do you get when you call a function before it is defined?
SyntaxError
Incorrect! A SyntaxError occurs when there is a mistake in your code's syntax. Try again.
IndexError
Incorrect! An IndexError occurs when you try to access an element of a container that doesn't exist. Try again.
NameError
Correct! This will cause a NameError because the function hasn't been defined yet.
TypeError
Incorrect! A TypeError occurs when a variable of an incorrect type is used in a function argument or operation. Try again.
See what happens if we move the function definitions around so that repeat_lyrics
is defined before print_lyrics
.
Checkpoint 5.7.2.
Q-5: Consider the code block below. What happens when you run this program?
def repeat_lyrics():
print_lyrics()
print_lyrics()
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
repeat_lyrics()
The lyrics print like normal.
Correct! This doesn't cause an error because both functions are defined before repeat_lyrics is called.
We get a TypeError.
Incorrect! This will not cause a TypeError because no invalid data types are used. Try again.
We get a NameError.
Incorrect! This will not cause a NameError because both functions are defined before repeat_lyrics is called. Try again.
The program compiles but nothing prints.
Incorrect! Something will be printed. Try again.
Checkpoint 5.7.3.
Construct a block of code with two functions. The first function is called printFlavors, which lists the available flavors. The second function should print the products and call the first function. Finally, call the second function. Watch your indentation! Hint: there is one unused code block.
def printFlavors():
---
print("Vanilla")
print("Chocolate")
print("Strawberry")
---
def printProducts():
---
print("Ice cream")
print("Milkshake")
print("Frozen yogurt")
print("************")
print("Flavors:")
printFlavors()
---
print("Ice cream")
print("Milkshake")
print("Frozen yogurt")
print("************")
print("Flavors:")
print(printFlavors()) #distractor
---
printProducts()