Exam4Training

How many stars will the following snippet print to the monitor?

How many stars will the following snippet print to the monitor?

i = 4

while i > 0:

i -= 2

print(‘*’)

if i == 2:

break

else:

print(‘*’)

The snippet will enter an infinite loop.
A . 0
B. 2
C. 1

Answer: C

Explanation:

Topics: if while break else (nobreak)

Try it yourself:

i = 4

while i > 0: # i is 4

i -= 2 # i is 2

print(‘*’) # *

if i == 2: # Yip, i is 2

break # Leave the loop directly

else: # Does not apply, because the break got triggered

print(‘*’)

In the first iteration the break gets directly triggered.

Therefore there will be only one star.

The else would only apply, if the break does NOT get triggered.

Exit mobile version