Exceptions & Files · Question 11 · Medium

Lines of numbers are read from a file-like object inside a with block and added up. What is the total?

import io

with io.StringIO("10\n20\n30") as f:
    total = sum(int(line) for line in f)
print(total)
  1. 102030
  2. ValueError
  3. 30
  4. 60
Answer and explanation

Answer: D. 60

Explanation: Iterating over a file gives one line at a time: '10\n', '20\n' and '30'. int() ignores surrounding whitespace, including the newline, so the values are 10, 20 and 30.

Previous: A custom exception carries a message built inside withdraw. What does printing… · Next: read() is called three times on the same file-like object, first with a size…

Practise exceptions & files

Try a fresh set of exceptions & files questions with an explanation after every answer, free and without signing up: Exceptions & Files practice. Or sit a full placement mock test.

More exceptions & files questions

More python practice

Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops · Functions & Scope · Comprehensions & Generators

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge