Loading video player…

What Does if __name__ == "__main__" Mean in Python? (Overview)

You’ve likely encountered Python’s if __name__ == "__main__" idiom when reading other people’s code. You might have even used if __name__ == "__main__" in your own scripts. But did you use it correctly?

This line of code can seem a little cryptic, so don’t fret if you’re not completely sure what it does, why you might want it, and when to use it.

In this video course, you’ll learn all about Python’s if __name__ == "__main__" idiom.


Sample Code (.zip)

3.2 KB

Course Slides (.pdf)

12.3 MB

00:00 Welcome to What Does if __name__ == "__main__" Do in Python? My name is Arianne, and I’ll be your instructor for this course.

00:09 Have you seen this code before? It’s an if statement checking if a variable called __name__ is equal to the string "__main__", and there are two underscores before and after name and main.

00:22 This strange-looking line of code pops up a lot in the Python world. Maybe you’ve seen it in a tutorial and had no idea what it did. Maybe you’ve used it in your own code without knowing why.

00:35 Perhaps you know another language that has a special main() function, and you’ve assumed this is the same thing, and maybe you know what it does, but not how it works or why it looks so unlike the clean, simple Python you’re used to. If so, you’ve come to the right place. In this course, you’ll find out the answers to these questions and more.

00:57 But first, saying if __name__ == "__main__" is a bit of a mouthful. For short, you can call it the name-main idiom, which is how we’ll refer to it in this course.

01:09 Here’s an overview of what you’ll learn throughout the course. In the next lesson, you’ll learn exactly what the name-main idiom does. Next, you’ll understand how it works.

01:21 Then, you’ll see when you should use it and when you should probably use something else. And then if you’re going to use it, you’ll get tips on how to use it well. Finally, we’ll review what you learned throughout the course, and you’ll get some additional resources to continue learning about related topics.

01:40 So let’s get started looking at what the name-main idiom does.

Become a Member to join the conversation.