Bird
0
0

What will this code print if 'numbers.txt' contains '1\n2\n3\n'?

medium📝 Predict Output Q5 of 15
Python - File Handling Fundamentals
What will this code print if 'numbers.txt' contains '1\n2\n3\n'?
with open('numbers.txt') as f:
    total = 0
    for line in f:
        total += int(line)
    print(total)
A6
B123
CError
D0
Step-by-Step Solution
Solution:
  1. Step 1: Loop through each line in the file

    Each line is '1\n', '2\n', '3\n'.
  2. Step 2: Convert each line to int and sum

    int('1\n') converts to 1, similarly 2 and 3, sum is 6.
  3. Final Answer:

    6 -> Option A
  4. Quick Check:

    Sum of lines as ints = 6 [OK]
Quick Trick: int() ignores trailing newline when converting [OK]
Common Mistakes:
  • Concatenating strings instead of summing
  • Not converting to int
  • Expecting error from newline

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes