[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 be 4 initially.
  • n = 2 * n - m: n will be 2 * 5 - 4, which is 6.
  • Output: 6 4
  • Then, m becomes 5, and n becomes 2 * 6 - 5, which is 7.
  • Output: 7 5
  • Then, m becomes 6, and n becomes 2 * 7 - 6, which is 8.
  • Output: 8 6
  • Since 8 >= 10, the loop stops. Therefore, it’s not infinite.
"Spread the light within, illuminate the hearts around you. Sharing is not just an action, but a sacred journey of connecting souls."~ Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *