Package logic into named, reusable pieces. Define functions, pass arguments, return results, and understand where variables live.
By the end of today you can
- Define and call functions with def
- Use positional, keyword and default arguments
- Return values, including several at once
- Explain local vs global scope
- Document a function with a docstring
You've been calling functions since Day 1: print(), len(), sorted(). Today you'll write your own. A function is a named, reusable recipe: give it inputs, it does some work, and it hands back a result.
Defining and calling
def starts the definition, the name follows the same rules as variables, and the body is indented. Nothing runs until you call the function with parentheses.
Parameters and arguments
Parameters are the names in the definition; arguments are the values you pass in:
Default values
Give a parameter a default and callers can leave it out:
return vs print
print only shows a value. return hands it back so the caller can use it:
Returning several values
Return a tuple and unpack it (Day 7):
Scope: where variables live
Variables created inside a function are local: they exist only during that call. The function can read variables from outside, but assigning to a name inside a function creates a new local one.
Docstrings
A string right after the def line documents the function. Tools and help() show it:
Functions calling functions
Small functions combine into bigger ones:
Recap
def name(params):defines a function; call it withname(args).- Arguments can be positional, keyword, or left out when there's a default.
returnhands a value back; without it a function returnsNone.- Variables inside a function are local; pass inputs in and return results out.
- Add a docstring to explain what a function does.
Knowledge check
Test what you learned
5 questions · pick an answer to see if you're right
- 1
What does a function return if it has no return statement?
- 2
def greet(name, greeting="Hello"). What does greet("Ada") return if the body is return f"{greeting}, {name}!"?
- 3
What is the difference between print() and return inside a function?
- 4
A variable created inside a function is...
- 5
Why are functions useful?
Finished today's lesson?