Beginning Python Programming—Part 5
By: Bob Roebling
Tags: Function, Python Programming, Python, Programming, Scope

Functions do not necessarily have to return a value. Instead, we could nest the print statement to handle error logging for us like this:

Now we have taken print("Aww...") and encapsulated it into a function that we can call any time we need to. This is called decomposition. If composition is building how a section of code works, decomposition is extracting the code re-used over and over again and making it easier to reference. For this simple example, we could have just written the print statement since it was only one line, but for the sake of brevity, perhaps a bit of laziness, this should be sufficient to get the idea.

By this function not returning a value, when it finishes we don’t have to use the return keyword. We can use the return, but by the time all of the code inside the body has been performed and we’ve reached the closing curly brace the function returns anyways. The only time you might use the return keyword in a function that doesn’t return a value is when you want to exit the function before all of the code has run.

NOTE: If you put in a return statement outside of a conditional check, certain editors such as PyCharm will state “This code may never be executed” or something to that effect. It’s just a tip saying “We know you did this, but here is an opportunity for you to clean up the code that will never be used, or fix your return statement so the code below has a chance to run.”

“So what’s up with the guitar Bob?” I didn’t just include the guitar at the top of the page for no reason. I wanted to give a real-world example of how functions should work.

Imagine, if you will, that guitar is perfectly tuned to A440, i.e. Concert A.

If I were to play the 1st string (the bottom E string), you would hear a perfect E note. No matter how many times I plucked that 1st string, you’d always hear the same perfect E. This is an example of a function. When we play the string, it vibrates at a certain hertz and returns sound. This could be relatable to the body and return of the function.

The general idea is that we don’t care how the function does stuff, we just want it to do what we expect when we call it.

One more thing…

If you know you want to use a function but haven’t quite figured out what it should do, you can use the pass keyword to skip execution of the function. This can also be used in if statements. As a quick example, check out this start for a function:

def calculate_driving_distance(starting_city, ending_city):

pass

Photo by Annie Spratt on Unsplash

Scope

On to the final section: scope. So far we have experienced scope. We experienced it with functions, if statements, while loops, and for loops. In a general sense, we’ve been covering it all along. So what is scope?

Scope defines where an object lives in code.

“OK Bob, you are crazy, you just told me an inanimate object has a life.” No really, in programs, we make them come to life, we make them perform work. Why not consider it this way:

Objects in code have a lifespan. For most of what we have been doing since the beginning, your variables have been created when the program starts, and when the program ends, they go away. That is considered the lifespan of an object.

When you create an object, which is just a general name encompassing things like variables and constants, it has a set lifespan. The lifespan of an object is determined by where it’s placed in the program. If you place an object on its own in a program like my_object: str = "Hello World" it will last for as long as the program is running. As soon as the program stops, my_object is removed from memory.

The problem is we can’t just load everything into memory. We’d run out of space, so we instead pick and choose what should be available at any given point in a program by defining its scope.

So I’ve talked about what scope is, but let’s see some practical examples of how scope can be defined and used in your code and how it makes you think about where to put your variables:

I’ve defined all kinds of levels of scope in this, so let’s start from the top.

my_global_integer is an object that can be used anywhere in code as long as the program is still running.

my_global_function is a function that can be used anywhere in code as long as the program is still running, however, the name variable inside of the body is only used inside of the body. As soon as the function exits, the name variable along with its value is removed from memory.

If we were to use the name variable outside of the function, Python would recognize it and automatically make a global variable at runtime. This could cause problems with memory efficiency; however, if you define name in one function and again in another, it will be used at a local function scope in each.

my_global_returning_function is exactly the same as my_global_function except it returns a value, and you might be keen to think it returns the variable created inside of the body because that’s what it returns, but it actually returns only the value of the variable. When the function reaches the end of the body, the variable name is removed from memory and you just have a copy of the value that you hopefully assigned to another variable.

Since we know that the returning function returns "Katy" this if statement would be comparing if "Katy" == "Katy", yes they are the same! So we reference back to the global_name variable from the global scope and grab the value from there (because we assigned a value before we performed the evaluation).

However, let’s say the name returned was something else like "Sophie" which is not the same as "Katy" . In the else statement, there is both a constant and a variable that are created and initialized. They can only be used while we are in curly braces of the else statement. If we were to have a variable created in the if portion of the if statement, it could only be used in the if portion.

We can still print my_global_variable and my_global_function , because they were defined outside of the body.

Something special about Python being an interpreted language is if I were to mistype my_global_integer on line 16 and use myGlobalInteger the program would still run.

Python does this because it doesn’t even know about lines it doesn’t use. This is different in compiled languages, as all lines are compiled down into byte code before they run. Since Python does all of its compilation at runtime, it only compiles what is needed and skips the rest.

If you forget everything else I said, just know that you can always go deeper with a variable, but you can never go outside of the body where the variable was initially declared.

Just imagine that whenever you leave the body that contains a variable, Bones says, “He’s dead, Jim!” Not much of a Star Trek fan? Well, I know a lot of people that like Hotel California and it works on much the same premise: you can never leave. Not an Eagles fan either? Well, I’m sure you can come up with your own mnemonic to help you remember how scope works if you feel like you need one.

And that is scope.

Summary

So today, with the help of tangled shoelaces, we realized the code we have written so far is a bit sloppy.

We started off with 3 principles to help us imagine how our code should look: Separation of Concerns, the Single Responsibility Principle, and Don’t Repeat Yourself.

We then talked about Functions and how they can help us abide by these principles. I strongly recommend you practice writing your own functions so you get the hang of it and understand what is and is not allowed. We learned about how to exit early from functions using return , and how to skip execution altogether with pass .

Finally, we talked about Scope. Just a tip, declare your variables at the lowest scope they will be used, then as you need the variable available in other places, move the declaration to a higher scope. As we move on, this will become more apparent in how we do this. I’m sure my future examples will do this.

Suggested Reading

Python Tutorial 4.5 through 4.7

What’s Next

You made it! Up next we will be talking about Classes, Properties, and Methods.

If you’ve been following along, you already know Properties and Methods. I just need to introduce you to Classes first.