Your first function
A function is a named block of code that performs a specific task. You define it once, then call it whenever you need that task done.Function syntax
Every function follows this pattern:def- keyword that creates a function- Function name followed by parentheses
() - Colon
:to start the function body - Indented code block (the function body)
Naming functions
Follow these rules for function names:- Use lowercase letters
- Separate words with underscores
- Be descriptive about what it does
Calling functions
To use a function, call it by name with parentheses:The power of functions: write once, use many times. The above code prints 6 lines with just 3 function calls!
Functions with logic
Functions can contain any Python code:Variable scope: Local vs Global
Variables in Python have a “scope” - where they can be accessed and used.Local variables
Variables created inside a function only exist within that function:Global variables
Variables created outside functions can be accessed anywhere:Modifying global variables
To change a global variable inside a function, use theglobal keyword:
Avoid using
global when possible. It makes code harder to understand and debug. Instead, pass values as parameters and return results.Best practice: Use parameters and returns
When a local and global variable have the same name, the local variable “shadows” the global one inside the function. Python always uses the local version first.
Common mistakes
Forgetting parentheses when calling
Forgetting parentheses when calling
Forgetting the colon
Forgetting the colon
Bad indentation
Bad indentation
What’s next?
Functions become powerful when they can accept input. Let’s learn about parameters!Parameters
Pass data to functions