Bird
Raised Fist0

What will be the output of this code if 'test.txt' contains the lines: 'cat', 'dog', 'bird'?

medium📝 Predict Output Q4 of Q15
Python - File Handling Fundamentals
What will be the output of this code if 'test.txt' contains the lines: 'cat', 'dog', 'bird'?
with open('test.txt', 'r') as f:
    lines = f.readlines()
    print(lines[1].strip())
Abird
Bcat
Cdog
DIndexError
Step-by-Step Solution
Solution:
  1. Step 1: Understand readlines() output

    readlines() returns a list of lines including newline characters.
  2. Step 2: Access second line and strip newline

    lines[1] is 'dog\n', strip() removes '\n', so output is 'dog'.
  3. Final Answer:

    dog -> Option C
  4. Quick Check:

    lines[1].strip() = 'dog' [OK]
Quick Trick: Indexing starts at 0; strip() removes newline [OK]
Common Mistakes:
MISTAKES
  • Forgetting strip() causes newline in output
  • Using wrong index
  • Expecting IndexError for valid index

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes