Skip to content

Question 14

What is the output of the following code?

1
2
3
4
5
6
ans, count = 0, 0
while count < 4:
    ans = (ans + count) * (-1)**count
    count += 1

print(ans)
Solution

Given ans = 0 and count = 0 from the start,

count < 4? ans = (ans + count) * (-1)**count
0 < 4 (True) (0 + 0) * (-1)**0
= 0 * 1
= 0
1 < 4 (True) (0 + 1) * (-1)**1
= 1 * (-1)
= -1
2 < 4 (True) (-1 + 2) * (-1)**2
= 1 * 1
= 1
3 < 4 (True) (1 + 3) * (-1)**3
= 4 * (-1)
= -4
4 < 4 (False) Final ans = -4
Answer
-4