Bird
Raised Fist0
Pythonprogramming~20 mins

__name__ and __main__ behavior in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Master of __name__ and __main__
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this code when run as a script?
Consider this Python script saved as script.py. What will it print when executed directly with python script.py?
Python
print(f"Top-level __name__ is: {__name__}")

if __name__ == "__main__":
    print("Running as main script")
else:
    print("Imported as a module")
A
Top-level __name__ is: __main__
Running as main script
B
Top-level __name__ is: script
Running as main script
C
Top-level __name__ is: __main__
Imported as a module
D
Top-level __name__ is: script
Imported as a module
Attempts:
2 left
💡 Hint
When a Python file is run directly, __name__ is set to "__main__".
Predict Output
intermediate
2:00remaining
What is the output when this module is imported?
Given the same code below saved as module.py, what will be printed when another script imports it using import module?
Python
print(f"Top-level __name__ is: {__name__}")

if __name__ == "__main__":
    print("Running as main script")
else:
    print("Imported as a module")
A
Top-level __name__ is: __main__
Running as main script
B
Top-level __name__ is: module
Running as main script
C
Top-level __name__ is: module
Imported as a module
D
Top-level __name__ is: __main__
Imported as a module
Attempts:
2 left
💡 Hint
When a file is imported, __name__ is the module's name, not "__main__".
🔧 Debug
advanced
2:00remaining
Why does this code print nothing when run directly?
This code is saved as test.py. When run with python test.py, it prints nothing. Why?
Python
def main():
    print("Hello from main")

if __name__ == "__main__":
    main
ABecause __name__ is not "__main__" when run directly.
BBecause main is referenced but not called (missing parentheses).
CBecause print statement is inside a function that is never defined.
DBecause the code has a syntax error and does not run.
Attempts:
2 left
💡 Hint
Check if the function main is actually executed.
📝 Syntax
advanced
2:00remaining
Which option causes a SyntaxError?
Which of these code snippets will cause a SyntaxError when run?
A
if __name__ = "__main__":
    print("Running")
B
if __name__ == "__main__":
    print("Running")
C
)"gninnuR"(tnirp    
:"__niam__" == __eman__ fi
D
if __name__ == "__main__":
    print("Running")
else:
    print("Not main")
Attempts:
2 left
💡 Hint
Check the operator used in the if condition.
🚀 Application
expert
2:00remaining
What is the output of this code when run directly?
Analyze this code saved as app.py. What will it print when executed with python app.py?
Python
def greet():
    print(f"Hello from {__name__}!")

if __name__ == "__main__":
    greet()
else:
    print(f"Imported module: {__name__}")
ANo output
BImported module: app
CHello from app!
DHello from __main__!
Attempts:
2 left
💡 Hint
Remember what __name__ is when running a script directly.

Practice

(1/5)
1. What does the special variable __name__ contain when a Python file is run directly?
easy
A. The file's directory path
B. The file's extension
C. "__main__"
D. The Python version

Solution

  1. Step 1: Understand the role of __name__

    When a Python file runs directly, __name__ is set to the string "__main__".
  2. Step 2: Differentiate direct run vs import

    If the file is imported, __name__ is the module's name, not "__main__".
  3. Final Answer:

    "__main__" -> Option C
  4. Quick Check:

    __name__ = "__main__" when run directly [OK]
Hint: Direct run sets __name__ to "__main__" [OK]
Common Mistakes:
  • Thinking __name__ holds file path
  • Confusing __name__ with Python version
  • Assuming __name__ is always module name
2. Which of the following is the correct syntax to run code only when a Python file is executed directly?
easy
A. if __name__ == '__main__':
B. if __main__ == '__name__':
C. if main == '__name__':
D. if __name__ = '__main__':

Solution

  1. Step 1: Check correct variable and string

    The variable is __name__ and the string to compare is "__main__".
  2. Step 2: Verify syntax correctness

    Use double equals == for comparison, and colons to start the block.
  3. Final Answer:

    if __name__ == '__main__': -> Option A
  4. Quick Check:

    Correct syntax uses == and exact names [OK]
Hint: Use if __name__ == '__main__': exactly [OK]
Common Mistakes:
  • Using single equals (=) instead of double (==)
  • Swapping __name__ and __main__
  • Missing colon at end of if statement
3. What will be the output when running this Python file directly?
def greet():
    print('Hello!')

if __name__ == '__main__':
    greet()
medium
A. Hello! Hello!
B. No output
C. Error: greet() undefined
D. Hello!

Solution

  1. Step 1: Check if condition when run directly

    Since the file runs directly, __name__ == '__main__' is True, so greet() is called.
  2. Step 2: Understand greet() function output

    The function prints "Hello!" once.
  3. Final Answer:

    Hello! -> Option D
  4. Quick Check:

    Function called once prints "Hello!" [OK]
Hint: Direct run triggers greet() printing once [OK]
Common Mistakes:
  • Thinking greet() runs twice
  • Assuming no output without main guard
  • Confusing function call with definition
4. Identify the error in this code snippet:
def main():
    print('Running main')

if __name__ = '__main__':
    main()
medium
A. IndentationError in function definition
B. SyntaxError due to single equals (=) in if condition
C. NameError because main() is undefined
D. No error, code runs fine

Solution

  1. Step 1: Check the if condition syntax

    The condition uses single equals (=) which is assignment, not comparison, causing SyntaxError.
  2. Step 2: Confirm function and indentation

    The function main() is defined correctly and indentation is fine.
  3. Final Answer:

    SyntaxError due to single equals (=) in if condition -> Option B
  4. Quick Check:

    Use == for comparison, not = [OK]
Hint: Use == in if condition, not = [OK]
Common Mistakes:
  • Using = instead of ==
  • Assuming function undefined error
  • Ignoring indentation correctness
5. You have two Python files:
# file1.py
def greet():
    print('Hi from file1')

if __name__ == '__main__':
    greet()

# file2.py
import file1
print('In file2')

What will be the output when you run file2.py?
hard
A. In file2
B. No output
C. Hi from file1
D. Hi from file1 In file2

Solution

  1. Step 1: Understand import behavior with __name__

    When file1 is imported, its __name__ is "file1", not "__main__", so greet() inside the if block does NOT run.
  2. Step 2: Check what runs in file2.py

    Only print('In file2') runs, so output is just "In file2".
  3. Final Answer:

    In file2 -> Option A
  4. Quick Check:

    Import skips main block, prints only file2 message [OK]
Hint: Imported file skips if __name__ == '__main__' block [OK]
Common Mistakes:
  • Assuming greet() runs on import
  • Expecting both prints always
  • Confusing __name__ values on import