0
0
Pythonprogramming~10 mins

__name__ and __main__ behavior in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A"__main__"
B"main"
C__main__
D"__name__"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the quotes around __main__
Using __main__ without quotes
Comparing to "main" instead of "__main__"
2fill in blank
medium

Complete 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'
A__main__
B"__name__"
C"__main__"
D"main"
Attempts:
3 left
💡 Hint
Common Mistakes
Calling greet() without the if condition
Using __main__ without quotes
Comparing to "main" instead of "__main__"
3fill in blank
hard

Fix 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'
A__main__
B__name__
C"__main__"
D"__name__"
Attempts:
3 left
💡 Hint
Common Mistakes
Printing the string "__name__" instead of the variable
Using __main__ variable which is undefined
Putting quotes around __name__
4fill in blank
hard

Fill 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'
A__name__
B"__main__"
C__main__
D"__name__"
Attempts:
3 left
💡 Hint
Common Mistakes
Using __main__ without quotes
Swapping the order of variable and string
Using "__name__" as string instead of variable
5fill in blank
hard

Fill 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'
Arun_task
B__name__
C"__main__"
Dmain
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong function name
Forgetting quotes around "__main__"
Calling function outside the if block