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_hello() not defined

Why is it not defined when we just imported it at the beginning?

def print_hello(): print("Hello from app.")
print_hello() if name == 'main':

import app

print("Hello from the second_app") print_hello()

3 Answers

Jamie Grant
Jamie Grant
1,605 Points

You're if statement logic is around the wrong way.

You've written -

print_hello() if name == 'main':

It should be

if name == 'main': print_hello()

Nick Evershed was trying to use the ternary operator for the if line, which is fine. However, there was a syntax error with that as no colons are needed and an "else ..." is required. For example, he can correct this syntax error by writing: print_hello() if name == "main" else print("") Note that what follows "else" cannot be keywords like "pass," "break," or "continue."

Order matters. There's also a syntax error with

__name__ == "__main__".  

Try copying it down exactly as he wrote it -- in two separate files. You can do this by pausing the video when the code is shown.

In app.py, print(__name__) is __main__. In second_app.py, print(__name__) is app.

I would guess the name is app because it is importing a file with filename "app" dot py. Because __name__ has two different results depending on import or not, you can check this.

if __name__ == "__main__":
    do_blah()

__name__ is only __main__ in app.py. Therefore, this code will only run if you are in app.py but not imports. This is useful because we want imports to behave differently in many cases.

Note that the function print_hello() is defined in app.py, not second_app.py. So, when calling it from second_app.py, you need to tell the machine that you want the print_hello() function from app.py by writing "app.print_hello()" rather than simply "print_hello()." (And, of course, the function must have been imported, which you have done.)