Functions (__main__)
We mentioned two lessons ago how we will include coding practices to help build good habits. Let's look at one advanced technique we may employ to help with this goal.
Let's run the following code first and see what prints out. Note that it uses something called a conditional statement, which we will learn in the Operators with Booleans lesson.
Now, let's slightly tweak the code and run it again to see what changes.
Let's go over this code now, starting with the most foreign looking part -
__name__
. This is a built-in variable that helps
us understand how a file is being used. If we're directly running a file,
__name__
will be "__main__". But, if our file is being used
by another file, __name__
won't be "__main__".
Why does this matter? It lets us decide which parts of our code run
depending on how the file is being used. If our file is the main one
being run, the code under if __name__ == "__main__":
(this conditional expression) will execute. Otherwise, if our file is
being used by another, it won't.
This technique is a common starting point in Python programs. From here, we can do various things like calling functions, creating objects, displaying messages, and more.
You might also wonder, "Why shouldn't I just put code outside of this special statement or outside of functions?" If we do that, the code will always run, whether you're directly running the file or it's being used by another file. This can lead to unexpected behavior, like the number two being printed in our second code example.
In simple terms, using this special statement helps us avoid unintentionally running parts of our code.
If all of this sounds a bit tricky, don't worry. We'll revisit this when we dive deeper into the topic of importing files in Python. For now, let's continue our exploration of functions.