Advanced Functions
Example¶
Another easy example is one that flips two variables. We take arguments a and b, but return b and a which we can then assign to a and b essentially flipping the two.
#You can return two arguments and have those two arguments be assigned to different variables
def switch(a, b):
return b, a
#Here we can overwrite the values of a and b with b and a (switching them)
a = 5
b = 10
#Switch the variables
a,b = switch(a,b)
print(a)
print(b)
Default Arguments¶
Sometimes we want to have an optional argument that takes a default value if nothing is passed for it. What about a multiplication function where we multiply a by b, but if we don't get b then we assume it is 2? The way we will set it up is by defining all required arguments followed by all optional ones. Optional ones will have the form of the argument name followed by an equal sign and the default values. Below, we define a multiplication function like we described.
#Define a function with a default argument for b
def multiply(a, b=2):
return a*b
When we just give one value it assumes b=2.
#So saying multiply 2 sets a=2 and b=2 by default
print(multiply(2))
In the case of changing this default value, we can pass in the variable the same kind of way we defined it above. Notice how the arguments are 2 and b=3. This makes it so b is no longer equal to the default value.
#Over-ride the default b values
print(multiply(2, b=3))
Function Scope¶
An important thing to understand with functions is the scope that functions work in. With the a lot of variables, if they are modified within the function they don't actually change outside of the function once it has ended. This is what the scope of the function means. Any new variables you define within a function also are not going to be there anymore once the function ends! This is why you need to return any values you want to keep.
Below we have a function that doubles a within the function and then prints it. Once the function has ended, a still equals 2 though.
#When you overwrite a value in a function, it is only modified within the function (usually)
#So setting a new value on a only changes it locally
def double(a):
a = a*2
print(a)
a = 2
double(a)
double(a)
double(a)
If you want to actually double the variable, you will need to return it and capture it in that same variable. Below is a way to achieve the desired effect of doubling it each time.
#If we wanted to actually keep doubling it, we would need to double within the function, return it then overwrite the
#current value
def double(a):
a = a*2
return a
a = 2
a = double(a)
print(a)
a = double(a)
print(a)
a = double(a)
print(a)