Loading
Loading
Loading
Loading
Loading
Loading
What are functions?
Back to AlgebraLet's forget about Python for a moment and go back a few years all the way back to Algebra. Do you remember any expressions that resemble the form of f(x) = x + 3
?
f(x) = x + 3
is a function. For any given x
, the function will add 3
to x
and return that value.
f(5) = 5 + 3
, returns8
f(10) = 10 + 3
, returns13
f(-3) = -3 + 3
, returns0
In mathematical terms, a function takes one or more inputs and produces an output. Our previous function f(x) = x + 3
can be broken down into:
f
in front of the parentheses is an arbitrary name used to represent a function. We can choose to rename our function to add_three
. This changes our function expression to add_three(x) = x + 3
.
A function can also take more than one input (e.g., add_three(a, b) = a + b
).
In programming, an inputs is referred as an argument, and an output is referred as a return value.
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Variable Scopes
Global ScopeAny variable that is declared outside of the function is in the global scope. A variable in the global scope is called a global variable. Both global_one
and global_two
variables in the code below are examples of global variables.
Loading
Variable Scopes
Any variable that is used inside a function is in the function scope. A variable in the function scope is called a local variable. When a function is called, a function scope for that function is created. The function scope includes both the arguments of the function and any variables created inside the function.
Loading
Loading
Python throws an error 🚫 since x
is already destroyed! Remember, function arguments reside in the local environment of the function and are destroyed once the function finishes running.