Updated: Aug 24, 2020
Functions will be one of our main building blocks when we construct larger and larger amounts of code to solve problems.
Formally, a function is a useful device that groups together a set of statements so they can be run more than once. They can also let us specify parameters that can serve as inputs to the functions.
On a more fundamental level, functions allow us to not have to repeatedly write the same code again and again. If you remember back to the lessons on strings and lists, remember that we used a function len() to get the length of a string. Since checking the length of a sequence is a common task you would want to write a function that can do this repeatedly at command.
Functions will be one of most basic levels of reusing code in Python, and it will also allow us to start thinking of program design.
Why even use functions ?
In simple terms , you should use functions when you plan on using a block of code multiple times. The function will allow you to call the same block of code without having to write it multiple times. This in turn will allow you to create more complex Python scripts.
Let's see how to build out a function's syntax in Python. It has the following form:
def name_of_function(arg1,arg2): ''' This is where the function's Document String (docstring) goes. When you call help() on your function it will be printed out. ''' # Do stuff here # Return desired result
We begin with def then a space followed by the name of the function. Try to keep names relevant, for example len() is a good name for a length() function. Also be careful with names, we wouldn't want to call a function the same name as a built-in function in Python (such as len).
Next come a pair of parentheses with a number of arguments separated by a comma. These arguments are the inputs for your function. We'll be able to use these inputs in your function and reference them. After this we put a colon.
Now here is the important step, we must indent to begin the code inside your function correctly. Python makes use of white space to organize code. Lots of other programming languages do not do this, so keep that in mind.
Next we'll see the docstring, this is where you write a basic description of the function. Docstrings are not necessary for simple functions, but it's good practice to put them in so we or other people can easily understand the code you write.
After all this you begin writing the code we wish to execute.
The best way to learn functions is by going through examples. So let's try to go through examples that relate back to the various objects and data structures we learned about before.
Simple example of a function
def say_hello(): print('hello')
Calling a function with ()
Call the function
If you forget the parenthesis (), it will simply display the fact that say_hello is a function. Later on we will learn we can actually pass in functions into other functions! But for now, simply remember to call functions with ().
Accepting parameters (arguments)
Let's write a function that greets people with their name.
def greeting(name): print( "Hello " + name)
So far we've only seen print() used, but if we actually want to save the resulting variable we need to use the return keyword.
Let's see some example that use a return statement. return allows a function to return a result that can then be stored as a variable, or used in whatever manner a user wants.
Example: Addition function
def add_num(num1,num2): return num1+num2
# Can also save as variable due to return result=add_num(4,5) print(result)
What happens if we input two strings?
Next Example - Check if any number in a list is even
Let's return a boolean indicating if any number in a list is even. Notice here how return breaks out of the loop and exits the function
def check_even_list(num_list): # Go through each number for number in num_list: # Once we get a "hit" on an even number, we return True if number % 2 == 0: return True # Don't do anything if its not even else: pass # Notice indentation! This ensures we run through entire for loop return False
Return all even numbers in a list
Let's add more complexity, we now will return all the even numbers in a list, otherwise return an empty list.
def check_even_list(num_list): even_numbers =  # Go through each number for number in num_list: # Once we get a "hit" on an even number, we append the even number if number % 2 == 0: even_numbers.append(number) # Don't do anything if its not even else: pass # Notice indentation! This ensures we run through entire for loop return even_numbers
nothing because no even number in the list.