if __name__ == “__main__”

Does your Python program always starts at the top of the file or can you tell Python where to start? Let's find out!

We'll cover the following

You will see a very common conditional statement used in many Python examples. This is what it looks like:

if __name__ == "__main__":
    # do something!

You will see this at the end of a file. This tells Python that you only want to run the following code if this program is executed as a standalone file. I use this construct a lot to test that my code works in the way I expect it to. We will be discussing this later in the course, but whenever you create a Python script, you create a Python module. If you write it well, you might want to import it into another module. When you do import a module, it will not run the code that’s under the conditional because __name__ will no longer equal "__main__". We will look at this again in Chapter 11 when we talk about classes.

Wrapping Up

We’ve covered a fair bit of ground in this chapter. You have learned how to use conditional statements in several different ways. We have also spent some time getting acquainted with Boolean operators.

Get hands-on with 1200+ tech skills courses.