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)
- 102030
- ValueError
- 30
- 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
- A try statement has except, else and finally clauses, and an error occurs in…
- An out-of-range list index is handled by two except clauses, the first naming…
- A custom exception carries a message built inside withdraw. What does printing…
- read() is called three times on the same file-like object, first with a size…
- Why is with open("data.txt") as f: preferred over calling open() and close()…
- The only except clause below names TypeError, but the conversion fails in a…
- readline() is called twice and then read() once on a three-line file-like…
- A function returns from inside try, and its finally block has a print. In what…
- All three parts of this try statement contain a return. What does risky() give…
- parse() catches one exception and raises a different one from its handler…
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