It helps your Python file know if it is being run directly or being used by another file. This way, you can control what code runs in each case.
__name__ and __main__ behavior in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
if __name__ == "__main__": # code to run only when file is executed directly print("Running directly")
__name__ is a special variable Python sets automatically.
When you run a file directly, __name__ equals "__main__".
Examples
__name__. If run directly, it prints __main__ and the message.Python
print(__name__) if __name__ == "__main__": print("This runs only when executed directly")
mymodule.py directly, it calls greet(). If imported, it does not run greet() automatically.Python
# file: mymodule.py def greet(): print("Hello!") if __name__ == "__main__": greet()
Sample Program
This program shows the value of __name__. If you run this file directly, it prints the message from main(). If you import it, only the print line runs showing the module name.
Python
def main(): print("This code runs only when the file is executed directly.") print(f"The __name__ variable is: {__name__}") if __name__ == "__main__": main()
Important Notes
When imported, __name__ equals the file name (without .py), not __main__.
This behavior helps separate reusable code from test or script code.
Summary
__name__ tells if a file is run directly or imported.
Use if __name__ == "__main__" to run code only when the file is executed directly.
This makes your code cleaner and more reusable.
Practice
1. What does the special variable
__name__ contain when a Python file is run directly?easy
Solution
Step 1: Understand the role of
When a Python file runs directly,__name____name__is set to the string "__main__".Step 2: Differentiate direct run vs import
If the file is imported,__name__is the module's name, not "__main__".Final Answer:
"__main__" -> Option CQuick 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
Solution
Step 1: Check correct variable and string
The variable is__name__and the string to compare is "__main__".Step 2: Verify syntax correctness
Use double equals==for comparison, and colons to start the block.Final Answer:
if __name__ == '__main__': -> Option AQuick 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
Solution
Step 1: Check if condition when run directly
Since the file runs directly,__name__ == '__main__'is True, sogreet()is called.Step 2: Understand greet() function output
The function prints "Hello!" once.Final Answer:
Hello! -> Option DQuick 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
Solution
Step 1: Check the if condition syntax
The condition uses single equals (=) which is assignment, not comparison, causing SyntaxError.Step 2: Confirm function and indentation
The functionmain()is defined correctly and indentation is fine.Final Answer:
SyntaxError due to single equals (=) in if condition -> Option BQuick 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:
What will be the output when you run
# 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
Solution
Step 1: Understand import behavior with __name__
Whenfile1is imported, its__name__is "file1", not "__main__", sogreet()inside the if block does NOT run.Step 2: Check what runs in file2.py
Onlyprint('In file2')runs, so output is just "In file2".Final Answer:
In file2 -> Option AQuick 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
