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?✗ Incorrect
When imported,
__name__ is set to the module's name, usually the filename without the .py extension.What happens to code inside
if __name__ == "__main__": when the script is imported?✗ Incorrect
Code inside this block runs only when the script is executed directly, not when imported.
Why do Python programmers use
if __name__ == "__main__":?✗ Incorrect
This condition ensures code runs only when the script is the main program, not when imported.
If you run a Python script directly, what will
print(__name__) output?✗ Incorrect
When run directly,
__name__ is set to "__main__".What is the main benefit of using
if __name__ == "__main__": in a Python file?✗ Incorrect
It allows the file to be imported without running main code, and also run as a standalone script.
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.