ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def walk(s):
    total = 0
    for i, ch in enumerate(s, start=1):
        if ch.isupper():
            total += i
        else:
            total -= i
    return total
print(walk('aBcD'))
  1. A. 0
  2. B. 2
  3. C. -3
  4. D. -4

Correct answer: B. 2

Positions 1 to 4 are a, B, c, D. Uppercase B and D add 2 and 4, while a and c subtract 1 and 3. The total is 2 + 4 - 1 - 3 = 2.

More Python Programming questions

Exams that ask this topic