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

print(__name__) in second_app.py prints out '__main__'. Why?

Because the print( __ name __ ) is outside a check in app.py it is run in second_app.py, and therefore it outputs ' __ main __ ' for app.py and 'app' for second_app.py. I inserted on purpose another print( __ name __ ) to second_app.py , right under the statement print("Hello from second_app.py"). The output for this new statement was ' __ main __ '. Since this is an import file and not app, why does it put out ' __ main __ ' instead of two times 'app'?

Steven Parker
Steven Parker
231,271 Points

I'm not sure I understand your description. Can you provide a link to a snapshot of your workspace?

https://w.trhou.se/q7vmy19z7p

Inserting print( __ name __ ) also in the script second_app.py, it outputs '__ main __' instead of 'app'

1 Answer

Steven Parker
Steven Parker
231,271 Points

So "second_app.py" is your main program (the one you run), and it imports "app". Perhaps it would help in understanding the output if we look at where each line of the output comes from:

Output Where It Comes From
workspace$ python second_app.py typed in to run the program
app line 4 of app.py ("print(__name__)")
Hello from second_app. line 3 of second_app.py
__main__ line 5 of second_app.py ("print(__name__)")
Hello from app. line 2 of app.py

So you can see that only the program that you run prints out "__main__" as the name. The imported one prints out the name of the file instead.

Oh I see. It is a little confusing but now it makes sense for me. Thank you Steven :)