Defining and calling
def stores a function. A call runs it.
def stores. greet() runs. Output: A, Hi, B.
A function is a block of code with a name. Follow the order in which these lines run. The def line only stores the function. Its body is skipped for now. So the first thing printed is A. Then comes the call: the name with parentheses. Python jumps into the body. The body prints Hi, and control goes back to the line after the call. Which prints B.
Defining and calling · Going deeper
Order of definition and call, and naming
Define before the call runs.
Return values
return hands a value back. print only shows it.
return gives the caller a value. No return gives None.
Returning and printing look alike on screen, and are quite different. This function returns the sum. The call is replaced by five, so x is five. Nothing is printed. This one prints the sum instead. Five appears on the screen, but nothing comes back, so y is None.
Return values · Going deeper
More about return
return ends the function at once.
Check yourself
What does this print?
Parameters and arguments
Arguments fill parameters by position, or by name
Positional, keyword, default.
This function has two parameters, and the second has a default value. Give one argument, and exp falls back on its default: three squared is nine. Give two, and they fill the parameters left to right. Name them, and the order no longer matters. Or mix the two styles, as long as the positional ones come first.
Parameters and arguments · Going deeper
Invalid calls, and sep and end
One value per parameter, or TypeError.
*args and **kwargs
* collects extra arguments in a tuple, ** in a dictionary
*args is a tuple. **kwargs is a dictionary.
Some functions accept any number of arguments. Call total with three numbers. The single star gathers them into one tuple named args. Now call info with two keyword arguments. The double star gathers them into a dictionary: each name is a key, each value its value.
*args and **kwargs · Going deeper
Combining them
Order: ordinary, *args, **kwargs.
Check yourself
What does this print?
Scope
A name made inside a function lives only inside it
Local x hides global x. Prints 5, then 10.
Where a name is created decides where it can be seen. This x is created at the top level, so it is global. The def line stores f. The call gives f its own, empty set of names. Assigning x inside f creates a new x there. The global one is not touched. Inside f, x is five. Back outside, the local x is gone, and x is still ten.
Scope · Going deeper
The global keyword, and what goes wrong
global x reaches the outer name.
Check yourself
What does this print?
Lesson complete
You finished “Functions”
Answer the questions along the way to see your score here.