0
0
Pythonprogramming~5 mins

__name__ and __main__ behavior in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the value of __name__ when a Python script is run directly?
When a Python script is run directly, the value of __name__ is "__main__". This means the script is the main program being executed.
Click to reveal answer
beginner
What does the condition if __name__ == "__main__": do in a Python script?
This condition checks if the script is being run directly (not imported). If true, the code inside the block runs. It helps separate code that should only run when the script is the main program.
Click to reveal answer
beginner
What is the value of __name__ when a Python file is imported as a module?
When a Python file is imported as a module, __name__ is set to the module's name (usually the filename without .py). It is not "__main__".
Click to reveal answer
intermediate
Why is using if __name__ == "__main__": useful in Python scripts?
It allows the script to be used both as a reusable module and as a standalone program. Code inside this block runs only when the script is executed directly, preventing it from running during import.
Click to reveal answer
beginner
Example: What will this code print if saved as example.py and run directly?<br>
print(__name__)
if __name__ == "__main__":
    print("Running directly")
Output will be:<br>
__main__
Running directly
<br>Because the script runs directly, __name__ is "__main__" and the condition is true.
Click to reveal answer
What does __name__ equal when a Python file is imported as a module?
A"__main__"
BNone
CThe module's filename without .py
DAn empty string
What happens to code inside if __name__ == "__main__": when the script is imported?
AIt runs immediately
BIt causes an error
CIt runs only if called explicitly
DIt does not run automatically
Why do Python programmers use if __name__ == "__main__":?
ATo run code only when script runs directly
BTo prevent syntax errors
CTo run code only when imported
DTo define global variables
If you run a Python script directly, what will print(__name__) output?
AThe script's filename
B"__main__"
CAn error
DNothing
What is the main benefit of using if __name__ == "__main__": in a Python file?
ATo allow the file to be both a module and a script
BTo make the script run faster
CTo avoid import errors
DTo automatically run tests
Explain what __name__ and __main__ mean in a Python script and why they are important.
Think about how Python knows if a file is run directly or imported.
You got /4 concepts.
    Describe a real-life scenario where using if __name__ == '__main__': helps in organizing Python code.
    Imagine you want to share functions but also test them in the same file.
    You got /3 concepts.