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
takes x
as an input and outputs x + 3
.
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
Slicing a List
Select SubsetIn Python, you can easily slice and retrieve a subset of a list
using the slice notation. The basic syntax is my_list[start:stop]
where my_list
is a list
-like value (or a variable). start
and stop
specify the index where you would like to start/stop retrieving values.
Slicing
my_list[start:stop]
retrieves all values fromstart
tostop - 1.
my_list[start:]
retrieves all values fromstart
to the end of the list.my_list[:stop]
retrieves all values from the beginning tostop - 1.
my_list[:]
retrieves all values from the list. This is often used to create a shallow copy of a list.
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.