ProgrammingHardTCS NQT · Infosys

What is printed?

What is printed?
total = 0
for s in ['10', '9', ' x', '+7', '1_0']:
    try:
        total += int(s)
    except ValueError:
        total -= 1
print(total)
  1. A. 34
  2. B. 36
  3. C. 35
  4. D. 25

Correct answer: C. 35

int accepts a leading plus sign and underscores between digits, and it ignores surrounding whitespace. Only ' x' fails, which subtracts 1, so 10 + 9 - 1 + 7 + 10 gives 35.

More Python Programming questions

Exams that ask this topic