Functions
Scope, parameters and arguments
|
A parameter, also called a formal argument, is a variable that is used within a function. ScopeWe looked at scope in Week 1 when learning about variables. Declare variables in the narrowest possible scope. For example, if a variable is used only inside a specific if statement, declare it inside that if statement rather than at the top of the function or the top of the Python file / class. Variables in functions only have local scope. This means they can only be accessed from inside that function. Global variables can be accessed from any location of a program. Due to the nature of Global variables, they should be used with careful consideration. You should never use the It is important to note that:
Parameters and argumentsTo pass values into a function, we use parameters / arguments. To pass values out of a function, we use a return value. |
|
Run the following code
When we call a function with parameters, we can pass a value to it. When we pass a value to a function, we call it an argument. The argument we are passing to the function
We have passed a value directly into a function. We can also pass the value contained in a variable as an argument to a function. In the following example, we will set three variables. Then, we will call our function three times, passing a different variable as an argument each time. It is important that you understand that it is the value contained in the variable that is passed, not the variable itself. However, in normal speech we just say we are passing the variable.
If a function has a parameter, and no argument is passed to the function when it is called, this will cause an error. |