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 trialEric Nachtsheim
2,006 PointsI'm not sure I wholly understand the if __name__ == '__main__': part of the code. What is it doing, precisely?
As I stated, the if name == 'main': part of the code confuses me. I understand practically that it's making it so that it returns True if the two words are equal, but I don't understand how.
1 Answer
Chris Freeman
Treehouse Moderator 68,457 PointsHey Eric Nachtsheim, good question!
During any python module execution, the value of __name__
is set to the name of the current .py module name. This is true for any imported module. The one exception to this is in the top level module name where __name__
is set to __main__
This allows for the if
condition you mention to be used to allow execution of code if and only if the current module was the top most module invoke from the OS command line.
Post back if you need more help. Good luck!!!
Andrew Leibowitz
2,529 PointsAndrew Leibowitz
2,529 PointsWhat does it mean if the current module is the top most module invoke from the Os command line? Sorry I'm a little confused.
Chris Freeman
Treehouse Moderator 68,457 PointsChris Freeman
Treehouse Moderator 68,457 PointsHey Andrew Leibowitz, when running Python code, each module run has the
__name__
attribute set to the name of the module. The exception is the module referenced on the command line. Itβs__name__
attribute is set toβ__main__β
to identify it as the top module involved by python interpreter.$ python some_module.py
While running
some_module
, it is treated as the top most module. Any other module imported modules would be beneath it.