Functions
Write a job once and use it whenever you need it. You'll define functions with def, hand them values with parameters, get answers back with return, give parameters defaults and call them by name, and see where a function's variables live. Then you'll write the functions behind a step-counter app.
Updated
Functions in Python
- What a Function Is: def and Calling (Novice): A function gives a job a name, written once with def and run whenever you call that name with parentheses, so a program does the same work in many places and changes it in one.
- Parameters and Return Values (Novice): Parameters let a function work on whatever values each call hands it, and return hands a result back to the code that called it, which is different from printing it and gives None when a function returns nothing.
- Default and Keyword Arguments (Apprentice): A default value lets a call leave an argument out, a keyword argument names the parameter it fills so the order no longer matters, and print() uses both in its sep= and end= arguments.
Where Variables Live
- Scope: Local and Global Variables (Apprentice): A variable made inside a function is local and disappears when the call ends, a variable made outside every function is global and can be read anywhere, and a function that takes values in and hands its result back is easier to trust than one that changes a global.
Exercise: Step Counter Functions
- Exercise: Step Counter Functions (Apprentice): Write the four functions behind a step-counter app's reports, with parameters, return values, a default and a keyword argument, and let pytest's tests call each one to check what it returns.