[Type B] Python Revision Tour-1 – Chapter 1
Table of Contents
5. Is the loop in the code below infinite? How do you know (for sure) before you run it?
m = 3
n = 5
while n < 10 :
m = n - 1
n = 2 * n - m
print(n, m)
The loop is not infinite. We can know this before running the code by analyzing the operations within the loop:
m = n - 1
:m
will be4
initially.n = 2 * n - m
:n
will be2 * 5 - 4
, which is6
.- Output:
6 4
- Then,
m
becomes5
, andn
becomes2 * 6 - 5
, which is7
. - Output:
7 5
- Then,
m
becomes6
, andn
becomes2 * 7 - 6
, which is8
. - Output:
8 6
- Since
8 >= 10
, the loop stops. Therefore, it’s not infinite.