Salvatore Lopiparo

Senior Software Engineer

Super Simple Python – Function and Variable Names

One of the best ways to keep your code clean and understandable is to use well defined function and variable names. Take, for example, the following bit of code:

1
2
3
4
5
6
7
def get_stuff(p, dirs=False):
    return_list = []
    for a, b, c in os.path.walk(p):
        return_list.extend(c)
        if dirs:
            return_list.extend(b)
    return return_list

It takes a lot of effort to figure out what is going on here. We can tell from the function name get_stuff that it’s used to get something, but what is it getting? The arguements p and dirs are very ambiguous. The p argument says nothing about what it is, and the dirs argument implies that it is a list of directories, but it’s actually a boolean! The a, b, and c variables have completely useless names. At least return_list tells us that it’s intended to be returned… though a good comment can do that much clearer!

Here’s the same function re-written with much more understandable function and variable names.

1
2
3
4
5
6
7
8
9
10
def get_file_names(path, include_directories=False):
    """
    Gets a list of all file names in the given path, including files in subdirectories.
    """
    list_of_file_names = []
    for root, dirs, file_names in os.path.walk(path):
        list_of_file_names.extend(file_names)
        if include_directories:
            list_of_file_names.extend(dirs)
    return list_of_file_names

For those people who are worried about the extra time they’re saving by using short names, think again! If you find a bug in the code or need to modify it in the future, trying to decipher the cryptic function will more than make up the difference in time. In addition, all modern IDEs (and even some text editors) have code completion, letting you only need to type a couple letters to fill out an entire variable name.

Super Simple Python #12 – Function Arguments

No, this is not about a function sleeping on the couch because it told another function what it really thought about that dress. Function arguments are the variables that you pass to a function. There are two basic kinds: arguments and keyword arguments.

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

The first kind, arguments, are what we have used thus far for passing variables to a function. These types of arguments are required to use the function.

1
2
3
def greeting(first_name, last_name):
    print("Hello " + first_name + " " + last_name + "!")
    print("How are you today?")

They are also ordered, meaning in our example that first_name must come first, followed by last_name.

4
5
6
7
8
>>> my_first_name = "Frank"
>>> my_surname = "Sinatra"
>>> greeting(my_first_name, my_surname)
Hello Frank Sinatra!
How are you today?

The other type of function arguments, keyword arguments, are not required. They let you have a default argument that can be changed if the calling function wants. These are denoted by giving the name of the keyword argument followed by the default value to use. name_of_dog is our keyword argument in this snippet, with an empty string being the default value.

1
2
3
4
5
def greeting(first_name, last_name, name_of_dog=""):
    print("Hello " + first_name + " " + last_name + "!")
    if name_of_dog:
        print("Hello to your dog, " + name_of_dog + ", too!")
    print("How are you today?")

This will allow us to call the function with or without name_of_dog, so we don’t have to write a separate function for each case (such as, greeting_with_dog and greeting_without_dog)!

6
7
8
9
10
11
12
>>> greeting("Frank", "Sinatra", name_of_dog="Fido")
Hello Frank Sinatra!
Hello to your dog, Fido, too!
How are you today?
>>> greeting("George", "Clooney")
Hello George Clooney!
How are you today?

Keyword arguments are not ordered. You can pass the keyword arguments in any order (as long as all the ordered arguments are first!). You can also skip some keyword arguments if you want to keep the default values.

1
2
3
4
5
6
7
8
9
def greeting(first_name, last_name, name_of_dog="", name_of_cat="", name_of_bird=""):
    print("Hello " + first_name + " " + last_name + "!")
    if name_of_dog:
        print("Hello to your dog, " + name_of_dog + ", too!")
    if name_of_cat:
        print("Your cat, " + name_of_cat + ", is looking sassy!")
    if name_of_bird:
        print("And let's not forget your bird, " + name_of_bird + "!")
    print("How are you today?")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> first_name = "Michael"
>>> last_name = "Jordan"
>>> 
>>> name_of_cat = "Sylvester"
>>> name_of_bird = "Tweety"
>>> 
>>> greeting(first_name, last_name)
Hello Michael Jordan!
How are you today?
>>> greeting(first_name, last_name, name_of_bird=name_of_bird, name_of_cat=name_of_cat)
Hello Michael Jordan!
Your cat, Sylvester, is looking sassy!
And let's not forget your bird, Tweety!
How are you today?

I have the sudden urge to watch Space Jam.

Super Simple Python #4 – Defining Simple Functions and Using The return Statement

One of the many cool things about Python is the really easy way to define functions. But before we can define any functions, we first need to define “function”! A function is a grouped bit of code that does some task. The print function in the last lesson is a function that outputs stuff to the console.

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

Here’s how we define a function of our own:

1
2
3
>>> def greeting():
...     print('Hello World!')
...

To define a function, we use the tag def followed by the name of our function. The code that the function performs comes after the line with the colon (:). All following lines must be indented by 4 spaces (if you’re using the PyCharm Console, you can press the Tab key instead).

Make sure you hit enter a couple of times until the “>>>” shows up again. The lines with “…” mean you are continuing a command on the next line, you should not type them. You’ve now defined a function! To use it, type:

1
2
>>> greeting()
Hello World!

We can also pass it an argument by adding it in the parentheses. This allows the function to get data from outside of itself:

1
2
3
4
5
>>> def greeting(name):
...     print("Hello " + name + "!")
...     
>>> greeting("Frank")
Hello Frank!

Most often you will want to have multi-line functions. At the beginning of each line after the function name, it must start with a 4 space indentation.

1
2
3
4
5
6
7
>>> def greeting(name):
...     print("Hello " + name + "!")  # Note the 4 spaces
...     print("How are you today?")  # 4 spaces here too!
...     
>>> greeting("Frank")
Hello Frank!
How are you today?

You will often need your function to have more than one variable available from outside. You can include more by separating them with commas. Remember that order matters!

1
2
3
4
5
6
7
>>> def greeting(first_name, last_name):
...     print("Hello " + first_name + " " + last_name + "!")
...     print("How are you today?")
...     
>>> greeting("Frank", "Morgan")
Hello Frank Morgan!
How are you today?

Most good functions have a return statement at the end. It does exactly that: returns what’s after the return to whatever called it. Like so:

1
2
3
4
5
6
>>> def adder(x, y):
...     new_number = x + y
...     return new_number
...     
>>> adder(2, 3)
5

The good thing about return statements is that they allow functions to put their result into a variable!

1
2
3
>>> eight = adder(3, 5)
>>> eight
8

A good function definition describes what the function does. Here’s our greeting function with a good description. We use 3 double-quotes in a row (which is just a string that can span more than one line) to describe the function.

1
2
3
4
5
def greeting(first_name, last_name):
    """Prints a greeting for the given first
    and last name."""
    print("Hello " + first_name + " " + last_name + "!")
    print("How are you today?")

Now the next person to look at this function won’t be confused about what it does!