Challenge - 5 Problems
Master of __name__ and __main__
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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")
Attempts:
2 left
💡 Hint
When a Python file is run directly, __name__ is set to "__main__".
✗ Incorrect
When you run a Python file directly, its __name__ variable is set to "__main__". So the first print shows __main__, and the if condition is true, printing "Running as main script".
❓ Predict Output
intermediate2: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")
Attempts:
2 left
💡 Hint
When a file is imported, __name__ is the module's name, not "__main__".
✗ Incorrect
When imported, __name__ is the module's filename without .py, here "module". So the first print shows "module" and the else branch runs, printing "Imported as a module".
🔧 Debug
advanced2: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
Attempts:
2 left
💡 Hint
Check if the function main is actually executed.
✗ Incorrect
The code references the function main but does not call it. It should be main() with parentheses to run the function and print the message.
📝 Syntax
advanced2:00remaining
Which option causes a SyntaxError?
Which of these code snippets will cause a SyntaxError when run?
Attempts:
2 left
💡 Hint
Check the operator used in the if condition.
✗ Incorrect
Option A uses a single equals sign (=) instead of double equals (==) in the if condition, which is invalid syntax in Python.
🚀 Application
expert2: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__}")
Attempts:
2 left
💡 Hint
Remember what __name__ is when running a script directly.
✗ Incorrect
When run directly, __name__ is "__main__", so greet() prints "Hello from __main__!".