Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to print a message only when the script is run directly.
Python
if __name__ == [1]: print("This script is run directly.")
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the quotes around __main__
Using __main__ without quotes
Comparing to "main" instead of "__main__"
✗ Incorrect
The special variable __name__ equals the string "__main__" when the script is run directly.
2fill in blank
mediumComplete the code to define a function and call it only when the script runs directly.
Python
def greet(): print("Hello!") if __name__ == [1]: greet()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling greet() without the if condition
Using __main__ without quotes
Comparing to "main" instead of "__main__"
✗ Incorrect
The function greet() should be called only if __name__ equals "__main__".
3fill in blank
hardFix the error in the code to print the module name when imported.
Python
print("Module name is", [1])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Printing the string "__name__" instead of the variable
Using __main__ variable which is undefined
Putting quotes around __name__
✗ Incorrect
The variable __name__ holds the module name or "__main__" if run directly.
4fill in blank
hardFill both blanks to create a script that prints differently when run or imported.
Python
def main(): print("Running as main script") if [1] == [2]: main() else: print("Imported as a module")
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using __main__ without quotes
Swapping the order of variable and string
Using "__name__" as string instead of variable
✗ Incorrect
The condition checks if __name__ equals the string "__main__" to run main().
5fill in blank
hardFill all three blanks to create a script that defines a function and runs it only when executed directly.
Python
def [1](): print("Function called") if [2] == [3]: [1]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong function name
Forgetting quotes around "__main__"
Calling function outside the if block
✗ Incorrect
Define function main(), check if __name__ == "__main__", then call main().