All modern programming languages have the concept of functions or methods. Functions and methods are the same things, but depending on the specific language you are using, they are called one or the other. Functions and methods are one way you can create reusable blocks of code. Then call them over and over throughout your application. Without writing the same code over and over again.
You may not realize it, but you have been using functions already. There are 68 built-in functions in Python. This in addition to any functions you get by importing modules or writing your own functions. When you type something like print(“Hello World!”), you are calling the print function, which in turn, writes the text out to your console screen.
The difference between the built-in functions in Python and. the functions we will be further discussing in this article are the built-in functions are written in C since Python is written in C. The rest of the functions we will be discussing in this article are going to be written in Python. If you are interested in looking at the source code for the built-in functions, you can find the source code on the Python GitHub page.
Defining the problem
Let’s assume we have a simple problem we need to solve. We have three lists of words and we want to print the word yes every time a color is listed in one of these lists. I have written some very inefficient code without using functions to solve this problem:
wordlist1 = 'red','car','kite','blue','yellow','house','mouse'
wordlist2 = 'balloon','car','truck','blue','green','house','horn'
wordlist3 = 'red','car','water','blue','fire','house','mouse'
for word in wordlist1:
if word == 'red':
print('yes')
if word == 'green':
print('yes')
if word == 'blue':
print('yes')
if word == 'yellow':
print('yes')
for word in wordlist2:
if word == 'red':
print('yes')
if word == 'green':
print('yes')
if word == 'blue':
print('yes')
if word == 'yellow':
print('yes')
for word in wordlist3:
if word == 'red':
print('yes')
if word == 'green':
print('yes')
if word == 'blue':
print('yes')
if word == 'yellow':
print('yes')
Notice how repetitive the above code is. We have four if statements that we repeat over and over again. If we get a fourth word list, we would need to copy/paste the for loop with all the if statements again. It doesn’t take long before this becomes completely unmanageable.
The second problem we have is if you want to make a change. Right now we only have four colors we are detecting: red, blue, green, and yellow. If we wanted to start looking for the word pink, we would need to add another if statement for each word list. That is 6 lines of code you have to write to add the color pink.
Creating a function
The solution to the problem outlined in the previous section is to write a function that checks a list and writes yes if it detects a color. Before we write a function to solve this specific problem, let’s look at the syntax for how you declare a function.
def hello_function():
print('hello function!')
hello_function()
In the above example, we declare a function called hello_function. All this function does is print the words “hello function!” on the screen. On the next line, after we declare the function, you can see how we use the function. If you run this code, you should see the words hello function! written to the console one time. For our next example, we are going to pass in a variable to our function.
def say_hello(name):
print("hello " + name)
say_hello('Bob')
In the example above, you can see we declare a function called say_hello and we add a variable called name. We then print the word hello and append the value of the name variable. On the third line of the script, we call the say_hello function and pass in the name bob. The output of the function will be “hello bob”
The original problem
Now that we know the basics of creating functions, let’s look at our original code again, and see how functions can make it better. In the original problem, we had a bunch of if statements that we repeated over and over again. Here is one of the examples
for word in wordlist1:
if word == 'red':
print('yes')
if word == 'green':
print('yes')
if word == 'blue':
print('yes')
if word == 'yellow':
print('yes')
We can wrap this block of code into a function, then call that function every time we want to perform this operation. Here is an example of how we might do that.
def detect_colors(wordlist):
for word in wordlist:
if word == 'red':
print('yes')
if word == 'green':
print('yes')
if word == 'blue':
print('yes')
if word == 'yellow':
print('yes')
wordlist1 = 'red','car','kite','blue','yellow','house','mouse'
detect_colors(wordlist1)
Notice in this example, we defined the function the same way as we did in our previous two examples. We added a variable called wordlist, and we passed in the original word list, just like we passed in the word bob in our previous example. Once the function is defined, we were able to just copy and paste our original for loop into our function. Now let’s refactor the entire original script using this function and look at how it compares.
def detect_colors(wordlist):
for word in wordlist:
if word == 'red':
print('yes')
if word == 'green':
print('yes')
if word == 'blue':
print('yes')
if word == 'yellow':
print('yes')
wordlist1 = 'red','car','kite','blue','yellow','house','mouse'
wordlist2 = 'balloon','car','truck','blue','green','house','horn'
wordlist3 = 'red','car','water','blue','fire','house','mouse'
detect_colors(wordlist1)
detect_colors(wordlist2)
detect_colors(wordlist3)
In this example we now have all three of our original word lists, and we call our detect_colors funciton three times. This has the same output as our original example. However, we do it with only 16 lines of code instead of 32. This menas we can easily add more word lists and our code will remain readable. If we want to detect additional color words, we can add them to the list of if statements in our function and it will automatically work everywhere we use our detect_colors function.
Python Function Return Values
In the previous examples of functions we were outputing to the screen by using the print function repeatedly. But this method of writing our functions can be fairly rigid. What if we want to take the output of one function, and utilize it in another function. In our next example, I have modified our original function to return a value instead of printing yes if a color is detected
def detect_colors(wordlist):
foundcolor = False
for word in wordlist:
if word == 'red':
foundcolor = True
if word == 'green':
foundcolor = True
if word == 'blue':
foundcolor = True
if word == 'yellow':
foundcolor = True
return foundcolor
wordlist1 = 'red','car','kite','blue','yellow','house','mouse'
wordlist2 = 'car','kite','house','mouse'
print(detect_colors(wordlist1))
print(detect_colors(wordlist2))
In this example I have added an extra variable, foundcolor, and set the value to false. We then run through our if statements and if our word matches any of the color words we have specified, then we set foundcolor = true. At the end, the function returns a value. At the bottom of the example you can see we have two wordlists. One list contains colors, the other does not. I call both functions and wrap the detect color function in a print function so the output will be displayed on the screen. When you run this, you should get an output of True False . This is because the function returned true for the first wordlist and false for the scond one.
Now that we have our function returning something, we can use this in all sorts of creative ways. Like we can do an if statemnt and call the function as part of the conditional statement of the if statement.
if detect_colors(wordlist1):
print("So Colorful!")
The above code will print “So Colorful!” if wordlist1 contains a color word. This is because the if statement is looking for a true or false input. Our function gives a true or false output…also known as boolean, which is exactly what the if statement wants.
Functions can return more than just true or false. You can return strings, numbers, etc… In this example, we have a function that returns the sum of two numbers, and will output 13 with the example input:
def add_numbers(x,y):
z= x+y
return z
print(add_numbers(6,7))
Or in this example, we have a function that returns a string based on the number you input into it. The output for this script will be “Hey There!” (we count from zero, so 2 is the third element in the list).
def select_greeting(x):
wordlist = 'hello','howdy','hey there!'
return wordlist[x]
print(select_greeting(2))
Summary
Today we covered why functions are useful in Python and other languages. We dicussed how to create a basic function, then use that knowledge to improve some inefficient code that we already had. After that we looked at how functions can return values, and we can utilize those values for various other tasks such as conditional statements.
We hope that you enjoyed this article. And please come back soon. You can join our mailing list if you would like to get notifications when we post new content.