Bird
0
0

Find the bug in this code:

medium📝 Debug Q7 of 15
Python - Context Managers
Find the bug in this code:
with open('log.txt', 'w') as f:
print('Writing to file')
f.write('Log entry')
AThe file mode 'w' is incorrect
BThe print statement is not indented inside the 'with' block
CThe write method is misspelled
DThe file name should be a variable
Step-by-Step Solution
Solution:
  1. Step 1: Check indentation rules

    Code inside a 'with' block must be indented to be part of the block.
  2. Step 2: Identify unindented print

    The print statement is not indented, so it is outside the 'with' block, likely causing logic errors.
  3. Final Answer:

    The print statement is not indented inside the 'with' block -> Option B
  4. Quick Check:

    Indent code inside 'with' block properly [OK]
Quick Trick: Indent all code inside 'with' block [OK]
Common Mistakes:
  • Not indenting code inside 'with'
  • Confusing file modes
  • Misspelling method names

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes