Bird
0
0

Which of the following is the correct way to execute code only when a Python script is run directly, not when imported?

easy📝 Syntax Q3 of 15
Python - Modules and Code Organization
Which of the following is the correct way to execute code only when a Python script is run directly, not when imported?
Aif __name__ == '__main__':
Bif __main__ == '__name__':
Cif __name__ != '__main__':
Dif main == '__name__':
Step-by-Step Solution
Solution:
  1. Step 1: Understand __name__ variable

    When a Python script runs directly, __name__ is set to '__main__'.
  2. Step 2: Check correct syntax

    The correct syntax to check this is if __name__ == '__main__':.
  3. Final Answer:

    if __name__ == '__main__': -> Option A
  4. Quick Check:

    Correct comparison operator and variable names used [OK]
Quick Trick: Use if __name__ == '__main__': to run direct script code [OK]
Common Mistakes:
  • Using single equals (=) instead of double equals (==)
  • Swapping __name__ and __main__
  • Using incorrect variable names like main or __main__

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes