Python Basics
Variables & Comments Math Operators Sequence Data Types Strings Lists & Tuples Logical Operators Conditional Statements Loops Functions
Data Wrangling
Pandas Introduction Importing Data Select, Drop & Rename Joining Data Cleaning Data Add Columns Dates
Visualisation
Coming Soon
Machine Learning
Coming Soon
Other Tutorials & Content
Python Data Science Reference Blog



Python Functions

In Python we use functions to perform some action or operation that we want to do more than once. We code the function and then call it with a single line of code whenever we need it. For example we could write a function that prints out the current date to the console. Functions can take some variables as inputs (known as parameters) to use inside the function and can also return an output after the action or operation has been performed. Functions can be as simple or as complex as required and can contain other functions (nested functions) as well as loops and if else statements.

Declaring a Function

def function_name(parameter1, parameter2):
#Some action or operation

We declare a function by using the keyword def followed by the function name and then a set of brackets where we declare the parameters we wish to pass to the function (oh and let’s not forget the colon). We define the action or operation below this and just like with loops and if else statements we must ensure that the code within the function is indented.

Finally we call the function by simply typing the function name followed by the required parameters in brackets.

function_name(x, y)

Now we’ve seen the structure of a function, let’s look at some actual examples.

A Simple Function

This function below is a simple example that takes an input called number and sets the binary variable to 1 if the value of the input is greater than zero or otherwise 0. Finally the function prints the value stored in the binary variable.

def convert_to_binary(number):
if number > 0:
output = 1
else:
output = 0
print("Output =", output)

convert_to_binary(10)
> Output = 1

Returning an Output

Functions can also return an output which can then stored in a variable and referenced in the rest of our script. We do this using the return keyword followed by the variable name we want to return. Below we modify the previous function to return the output into a variable called binary.

def convert_to_binary(number):
if number > 0:
output = 1
else:
output = 0
return output

binary = convert_to_binary(10)
print("Output =", binary)
> Output = 1

We can in practice create as many different variables as we need by using the same function but perhaps with different parameter values. This is one of the main reasons that functions are useful and a very efficient way to write code.

Returning Multiple Outputs

One other useful aspect of Python functions is that we’re not limited to returning just one output. Functions can return multiple outputs that can each be assigned to different variables. In the below example we pass a number to a function that returns both the square and cube of that number which we then store in separate variables.

def get_square_and_cube(number):
square = number ** 2
cube = number ** 3
return square, cube

six_squared, six_cubed = get_square_and_cube(6)
print(six_squared)
print(six_cubed)
> 36
> 216

Local & Global Variables

Now you may have noticed that in some of the examples so far we have been assigning new variables inside functions but it’s worth pointing out that these don’t exactly behave like variables we’ve been dealing with before and that’s because they don’t have scope that ordinary variables do. If we declare a new variable in the function like we did with the square variable in the previous example, then this is called a local variable, meaning that it’s limited to being used only in the function in which it’s declared. Global variable are ones we declare in the main regular part of our code as we have seen previously and can be referenced from anywhere.

If we try to reference a local variable outside of the function it’s declared in then we will get a NameError. Let’s try to do this now with the square variable we declared previously in the get_square_and_cube function from the example above.

print(square)
> NameError: name 'square' is not defined

Default Parameters

When we declare a function with parameters you are basically telling Python that it needs those parameters for the function to work correctly and therefore will error if it isn’t given the values it needs. Sometimes however, the parameter we pass will often end up being the same value and so rather than passing it every time, we can set the parameter to a default value that means if we don’t pass a value when we call the function then Python will just use this instead. Of course, when we do this we still have the option to pass a different value if required when we call the function.

In the example below we have created a function that calculates the tax for a given value. As most of the time we believe the tax rate we need is 20% then we have set the default value to 0.2 for tax_rate by assigning it in the parameter list when we declare the function. Now when we call the function with only the value parameter then Python will use 0.2 for the tax_rate.

def tax_calculator(value, tax_rate=0.2):
tax = value * tax_rate
return tax

my_tax = tax_calculator(1000)
print(my_tax)
> 200.0

If we decide on a different tax_rate, such as 0.3, then we can still pass this value as a parameter and Python will use this instead.

my_tax = tax_calculator(1000, 0.3)
print(my_tax)
> 300.0

Exercises

1. Write a function that takes two strings as inputs and returns the concatenation of the two strings to a new variable.

2. Write a function that takes a list of numbers containing the numbers 1 to 4 as an input and returns a new list that that contains the square of all the numbers in the input list. (Hint: You could use a For loop here).

Solutions

#Exercise 1
def string_concatenator(string1, string2):
concatenated_string = string1 + string2
return concatenated_string

print(string_concatenator('Concatenated ', 'string'))
> Concatenated string
#Exercise 2
def square_list(list_of_numbers):
square_numbers = []
for number in list_of_numbers:
square_numbers.append(number ** 2)
return square_numbers

numbers = [1, 2, 3, 4]
numbers_squared = square_list(numbers)
print(numbers_squared)
> [1, 4, 9, 16]
Next