Member-only story
1. How many times does the following loop execute?
i = 0
found = False
while i < 100 and found != True :
i = i + 1
print(i, end = " ")
j = i * i
if i * i * i % j == j :
found = True
An infinite number of time
- Initially,
i
is set to 0, andfound
is set to False. - The loop condition
i < 100 and found != True
checks two conditions: whetheri
is less than 100 and whetherfound
is not equal to True. - Inside the loop,
i
is incremented by 1 in each iteration (i = i + 1
). - Then,
j
is calculated as the square ofi
. - The if condition
if i * i * i % j == j
is checked. This condition will always be true becausei * i * i
is always divisible byj
(which isi * i
). - As a result,
found
is set to True. - However, since the loop condition checks both
i < 100
andfound != True
, andi
is incremented in each iteration,i
will eventually reach a value greater than or equal to 100, but the loop will continue to execute because the conditionfound != True
remains true due tofound
being set to True only after the if condition inside the loop.