Functions: Reusable Code
A function is a named, reusable block of code. Instead of repeating the same lines, you write them once inside a function and call it whenever you need it. Functions are how real programs stay organized as they grow, and they power the capstone project at the end of this module.
What You'll Learn
- Defining and calling functions
- Passing information in with parameters
- Default values and keyword arguments
- Getting information back with
return
Defining and Calling
Use def, a name, parentheses, and a colon. The indented lines are the function body. Nothing runs until you call it:
Parameters
A parameter lets you pass information into a function. The value you pass in is called an argument:
Default Values
A parameter can have a default that is used when no argument is given:
return: Sending a Value Back
print() shows something on screen. return hands a value back to the caller so you can store it or use it in more code. This difference is crucial:
return Ends the Function
As soon as a return runs, the function stops. This lets you handle edge cases early:
Functions Calling Functions
Small functions combine into bigger behavior. You will lean on this in the capstone:
Key Takeaways
def name():defines a function; call it withname()- Parameters pass data in; arguments are the values you pass
- Defaults:
def f(x=10) returnsends a value back;printonly displaysreturnends the function immediately- Functions can call other functions

