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 Writing to Files

if __name__ == '__main__':

why we are using it when we can just call the function normally

1 Answer

Christopher Shaw
seal-mask
PLUS
.a{fill-rule:evenodd;}techdegree seal-36
Christopher Shaw
Python Web Development Techdegree Graduate 58,248 Points

The code here is executed when the file is 'run' from the command line. for example if we had a file called hello.py with the following contents. When you run python hello.py from the command line, it will excute main_function(). However if you import hello.py, it will not run.

def main_function():
    print("Hello World")

if __name__ == '__main__': 
    main_function()

To add onto this answer. Lets pretend we have a two files called import_me.py and test_me.py that looks like this.

import_me.py

def print_hello():
    print("Hello")

print("this is import_me.py")
print_hello()

Now from another file called, lets say test_me.py

test_me.py

import import_me

print("This is the test_me.py Script")

I would tell Python to run the test_me.py script

python test_me.py

You would get this output.

Output

this is the import_me.py
Hello
This is the test_me.py Script