Bird
0
0

You have two Python files:

hard📝 Application Q15 of 15
Python - Modules and Code Organization
You have two Python files:
# file1.py
def greet():
    print('Hi from file1')

if __name__ == '__main__':
    greet()

# file2.py
import file1
print('In file2')

What will be the output when you run file2.py?
AIn file2
BNo output
CHi from file1
DHi from file1 In file2
Step-by-Step Solution
Solution:
  1. Step 1: Understand import behavior with __name__

    When file1 is imported, its __name__ is "file1", not "__main__", so greet() inside the if block does NOT run.
  2. Step 2: Check what runs in file2.py

    Only print('In file2') runs, so output is just "In file2".
  3. Final Answer:

    In file2 -> Option A
  4. Quick Check:

    Import skips main block, prints only file2 message [OK]
Quick Trick: Imported file skips if __name__ == '__main__' block [OK]
Common Mistakes:
  • Assuming greet() runs on import
  • Expecting both prints always
  • Confusing __name__ values on import

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes