A function is a named block of code that performs a specific task. Instead of writing the same code over and over, you write it once in a function and call it whenever you need it.
Use the def keyword, followed by the function name, parentheses, and a colon:
Defining a function (def greet():) creates the function but doesn't run it.
Calling a function (greet()) actually executes the code inside.
You must define a function BEFORE you call it!
Same as variables: lowercase, underscores between words, descriptive names:
Create and call your own function! Functions help you organize and reuse code.
Define a function called introduce that prints "My name is [Your Name]" and "I am learning Python!". Then call the function.
You can define and call functions. Now let's make them flexible with parameters!
Parameters are variables that receive values when a function is called. They make functions flexible - you can pass different data each time!
Define parameters inside the parentheses:
Parameter: The variable in the function definition (name in def greet(name))
Argument: The actual value passed when calling ("Alice" in greet("Alice"))
Think: Parameters are placeholders, arguments are the real values.
Functions can have multiple parameters, separated by commas:
When calling a function, arguments are matched to parameters by position. create_profile("Alice", 25, "NYC") maps Alice→name, 25→age, NYC→city. Wrong order = wrong results!
Create a function that takes parameters and uses them to customize output.
Create a function calculate_area that takes length and width parameters and prints the area of a rectangle. Test it with different values.
You can pass data into functions. Now let's learn how to get data back out!
So far, our functions have printed output. But often we want functions to calculate something and give us the result back. That's what return does!
print(): Displays text on screen. The value is lost - you can't use it further.
return: Sends a value BACK to the caller. You can store it, use it in calculations, pass it to other functions.
Rule of thumb: Use return for calculations, print() for displaying to users.
Python functions can return multiple values as a tuple:
return immediately exits the function. This is useful for handling special cases:
Create functions that return values instead of just printing them.
Create a function calculate_grade that takes a score and returns the letter grade: A (90+), B (80-89), C (70-79), D (60-69), F (below 60). Test it with scores 95, 82, and 55.
You can get data back from functions. Let's explore advanced parameter techniques!
Python offers powerful ways to make function calls more flexible and readable.
Set default values for parameters - they're used if no argument is provided:
Parameters with defaults must come AFTER parameters without defaults.
def greet(greeting="Hi", name): ← This causes an error!
def greet(name, greeting="Hi"): ← This is correct!
When calling a function, you can specify arguments by name:
Use keyword arguments when:
• Function has many parameters (improves readability)
• You want to skip optional parameters
• The parameter meaning isn't obvious from the value
Example: create_user("Bob", 30) vs create_user(name="Bob", age=30)
Create a function with default parameters to make it flexible.
Create a function power that calculates base raised to exponent. Make exponent default to 2 (square). Test with power(5), power(2, 3), and power(10, exponent=4).
You know defaults and keywords. One more important topic - scope!
Scope determines where a variable can be accessed. Variables created inside a function have local scope - they only exist inside that function.
Local variables: Created inside a function, only accessible inside that function.
Global variables: Created outside functions, accessible everywhere (for reading).
Parameters: Act like local variables - only exist inside the function.
To modify a global variable inside a function, use the global keyword:
While global exists, using it is generally bad practice. It makes code harder to understand and debug. Better approach: pass data through parameters and return values!
Practice working with local and global variables to understand scope.
Predict what this code will print, then run it to verify. The code demonstrates local vs global scope:
You understand where variables live. Time for the summary!
Congratulations! You've mastered functions - one of the most important concepts in programming. Let's recap:
def, call with function_name()returnCreates a reusable block of code with a name.
Variables that receive values when the function is called.
Sends a value back. Different from print() which just displays.
Local variables stay inside functions. Avoid globals!
Functions are the building blocks of organized code. Ready to prove your skills?