Bird
Raised Fist0

You want to write a Python script that can be used both as a module and run directly. Which code structure correctly achieves this?

hard🚀 Application Q9 of Q15
Python - Modules and Code Organization
You want to write a Python script that can be used both as a module and run directly. Which code structure correctly achieves this?
def process():
    print('Processing')

# Which block below is correct?
Aif __name__ != '__main__': process()
Bif __name__ == 'main': process()
Cif __name__ == '__main__': process()
Dif __name__ == '__module__': process()
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct __name__ check for direct run

    The correct string to check is "__main__" with double underscores on both sides.
  2. Step 2: Confirm correct if condition

    Only if __name__ == '__main__': runs code when script is executed directly.
  3. Final Answer:

    if __name__ == '__main__': process() -> Option C
  4. Quick Check:

    Use '__main__' with double underscores for direct run check [OK]
Quick Trick: Use '__main__' with double underscores for direct run check [OK]
Common Mistakes:
MISTAKES
  • Using 'main' without underscores
  • Using '!= __main__' which runs on import
  • Using '__module__' which is invalid

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes