Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Conditional Check

Elena Chen
Elena Chen
1,503 Points

Watched several times of the dunder main but still don't get it

  1. Do we have to use this conditional check for every function we create/use?
  2. Where should we put the conditional check every time? Is it part of the function body or just before we call this function like the instructor did in this video?

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,454 Points

Good question! The dunder main code, or module __name__ check block is used to isolate code that should only be run if the module is executed as the top level module.

That is, if my_module.py has code that should only be executed when the module is run using python my_module then it is placed in the module __name__ check block. This prevents this module level code from running if the module is imported using import my_module.

If a module is imported, the module’s __name__ attribute is set to the name of the file. So if the file my_module.py was imported using import my_module then my_module.__name__ would be set to “my_module”.

If run directly using python my_module.py then the value __name__ would be set to “__main__”.

Post back if you need more help. Good luck!!!

That Youtube video did it for me! They should hire that guy!

Clayton McDaniels
Clayton McDaniels
5,788 Points

Team Treehouse this needs to be explained better maybe in a longer video with in depth explanation. The youtube video posted helped me more.

Thanks for the youtube link...that helped me understand.