A function is a reusable block of code that performs a specific task.
Functions help you:
In Python, functions are created using the def keyword.
A function does not run automatically. You must call the function by writing its name followed by parentheses.
A parameter is a variable listed in the function definition.
An argument is the actual value passed into the function when it is called.
You can:
The return keyword sends a value back from a function.
This is different from print(). Printing only displays a value, while returning lets you store and reuse it.
You can:
print() displays information to the screen. return gives a value back to the program.
Use return when you need the result later.
A default parameter gives a parameter a backup value.
If the function is called without an argument, Python uses the default value.
You can:
Keyword arguments let you pass values using parameter names.
This makes function calls easier to understand, especially when there are multiple parameters.
You can:
*args lets a function accept multiple positional arguments.
Python stores these extra arguments inside a tuple.
You can:
**kwargs lets a function accept multiple keyword arguments.
Python stores these arguments inside a dictionary.
You can:
Scope describes where a variable can be used.
A variable created inside a function is called a local variable. A variable created outside a function is called a global variable.
You can:
Prompt: Create a function called calculate_average that takes a list of grades and returns the average. Then, use the function to print each student's name and average grade.
Target Output:
Alice: 87.5 Bob: 91.5
Ask the AI if you need help understanding or want to dive deeper in any topic