Skip to content
Home » Functions in Python – Introduction to Functions

Functions in Python – Introduction to Functions

Spread the love

We’ve been talking about functions in Python a lot. But let’s try to systematize everything we know about them. Today we’ll start talking about the very basics of functions and in some future articles we’ll go into much more detail. So, if you know the basics of functions, there isn’t going to be much fun for you in this article and maybe you should move on to some more advanced stuff. But, on the other hand, you may want to recap on the basics as well, so feel free to do so.

Repetitive Code vs DRY Code

dry code

Before we move on to discuss functions in Python, let’s have a look at the following code:

alphabet = "abcdefghijklmnopqrstuvwxyz"

print("Here is the alphabet:")
print()
for letter in alphabet:
    if letter != "z":
        print(letter, end = "*")
    else:
        print(letter)
print()

again = input("Do you want me to print the alphabet in such a fancy way again (yes / no)?")
print()
if again == "yes":
    print("Here is the alphabet:")
    print()
    for letter in alphabet:
        if letter != "z":
            print(letter, end = "*")
        else:
            print(letter)
    print()
else:
    print("I don't accept a no. Now I'll do it twice!!!")
    print()

    print("Here is the alphabet:")
    print()
    for letter in alphabet:
        if letter != "z":
            print(letter, end = "*")
        else:
            print(letter)
    print()

    print("Here is the alphabet:")
    print()
    for letter in alphabet:
        if letter != "z":
            print(letter, end = "*")
        else:
            print(letter)
    print()

This code is very simple. It just prints the alphabet in a fancy way. I used the end parameter to add the stars. Here’s the output:

Here is the alphabet:

a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z

Do you want me to print the alphabet in such a fancy way again (yes / no)?no

I don't accept a no. Now I'll do it twice!!!

Here is the alphabet:

a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z

Here is the alphabet:

a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z

This code works, but what if we wanted to make a change and separate the letters with dollar signs instead of asterisks? Easy, we would have to make the change four times in the code. Well, four times the same. What if the same code were repeated 20 or 100 times in the program? What if there were more changes to make? Now it doesn’t look that simple anymore. Even worse, what if after making all those changes you notice that you made a mistake somewhere? Then you would have to go over all the repeating pieces of code again and correct them. Sounds like there must be a better way of doing this. And there is. Repetitive code is bad and should be avoided. Good code should be DRY (= Don’t Repeat Yourself). Each piece of code should be written only once, in one place, so that if any changes are necessary, we only need to make them in one place. The solution to that are functions.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

What is a Function?

functions in Python

A function is a piece of code consisting of multiple statements that has a name and can be used multiple times in our code. Instead of writing all the statements all over again where needed, we just use the name of the function with parentheses to run them. We then say that we call the function. So, calling a function consists in running the statements which belong to it.

Using functions makes the code more readable and much more maintainable. If you need to make a change, you make it only in one place, in the definition of the function. After that, the change takes effect whenever we call the function.

There are lots of built-in functions in Python, like print, len, all, any, help, dir or upper, to mention just a few. But we can define our own functions. Such functions are called user-defined functions.

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Defining a Function

So, how do we define a function? In the simplest scenario we use the following syntax:

def name():
    statement1
    statement2
    ...

First of all, we need the def keyword, which means we are beginning to define a function. Then comes the name of the function, which will be later used to call the function. After the name there is a pair of parentheses. Sometimes there is something in the parentheses, but in the simplest example there may be nothing. Anyway, we must use them, even if empty. Then comes the colon and in the next line we can start with all the statements that build the body of the function.

Back to our example. We can easily find the piece of code which is repeated. Here it is:

print("Here is the alphabet:")
print()
for letter in alphabet:
    if letter != "z":
        print(letter, end = "*")
    else:
        print(letter)
print()

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Let’s turn it into a function. We say, we’re extracting a function. A good name seems to be fancy_alphabet. Here’s the definition:

def fancy_alphabet():
    print("Here is the alphabet:")
    print()
    for letter in alphabet:
        if letter != "z":
            print(letter, end = "*")
        else:
            print(letter)
    print()

Calling a Function

Now we can rewrite our code using the function. We just have to call the function whenever the repeated code was used. Changing the form of your code so that it has a different structure but still does the same job is called refactoring. So, let’s refactor our code by first defining the function and then calling it when needed:

def fancy_alphabet():
    print("Here is the alphabet:")
    print()
    for letter in alphabet:
        if letter != "z":
            print(letter, end = "*")
        else:
            print(letter)
    print()

alphabet = "abcdefghijklmnopqrstuvwxyz"

fancy_alphabet()

again = input("Do you want me to print the alphabet in such a fancy way again (yes / no)?")
print()
if again == "yes":
    fancy_alphabet()
else:
    print("I don't accept a no. Now I'll do it twice!!!")
    print()

    fancy_alphabet()
    fancy_alphabet()

Now, if you run the code, you’ll get the same output. Suppose you wanted to change the asterisks to dollar signs. All you have to do is make the change in the function body:

def fancy_alphabet():
    print("Here is the alphabet:")
    print()
    for letter in alphabet:
        if letter != "z":
            print(letter, end = "$")
        else:
            print(letter)
    print()

If you now run the program, a possible output could be:

Here is the alphabet:

a$b$c$d$e$f$g$h$i$j$k$l$m$n$o$p$q$r$s$t$u$v$w$x$y$z

Do you want me to print the alphabet in such a fancy way again (yes / no)?yes

Here is the alphabet:

a$b$c$d$e$f$g$h$i$j$k$l$m$n$o$p$q$r$s$t$u$v$w$x$y$z

PEP 8 Guidelines for Functions in Python

Here are some PEP 8 guidelines for functions in Python. They should be followed for good coding style:

– We should separate functions from the rest of the code, also from other functions, by a blank line.

– We should also use blank lines to separate larger blocks of code inside functions.

– We should put comments on separate lines if possible.

– We should use docstrings.

– We should use spaces before and after operators, so rather a + b than a+b.

– We should also use spaces after commas: print(a, b, c) and not print(a,b,c).

– We shouldn’t use spaces after opening and before closing parentheses, brackets or braces, so multiply(3, 5) is OK, whereas multiply( 3, 5 ) isn’t.

– We should use lowercase names for functions, with underscores to separate words, like for example remove_odd_numbers() rather than RemoveAllNumbers().


Spread the love

Leave a Reply