Welcome to the lesson on Python Functions
Functions
A function is a block of code which only runs when it is called.
Creating Functions
In Python a function is defined using the def keyword:
Example:
Calling a Function
To call a function, use the function name followed by parenthesis:
Examples:
Arguments
Information can be passed into functions as arguments.
Examples:
Parameters or Arguments?
A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that is sent to the function when it is called.
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
Examples: This function expects 2 arguments, and gets 2 arguments:
If you try to call the function with 1 or 3 arguments, you will get an error:
Examples:
Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
Examples:
Default Parameter Value
The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
Examples:
Passing a List as an Argument
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
if you send a List as an argument, it will still be a List when it reaches the function
Examples:
Return Values
To let a function return a value, use the return statement:
Examples:
The pass Statement
function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error
Examples:
End of Python Functions
You have learned Functions in simple terms. Let's proceed on to Quiz.