Web Analytics Made Easy -
StatCounter Python: Can any one explain this while loop. - CodingForum

Announcement

Collapse
No announcement yet.

Python: Can any one explain this while loop.

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Python: Can any one explain this while loop.

    This seems like an easy one. My doubt is, when is "num" changing its value.


    def nearest_square(limit):
    num = 0
    while (num+1)**2 < limit:

    print(num)
    num += 1
    print(num)
    return num**2


    limit = 20
    print(nearest_square(limit))

    OUTPUT:
    0
    1
    2
    3
    16


    In the code I am incrementing "num" twice. (Once in the condition of while loop and second inside the while loop)

  • #2
    You're not incrementing num in the condition of the while loop. You're creating a new value. That new value is never reassigned to num, so num doesn't change there. Note the different operators, "+" vs "+=".

    Comment


    • #3
      In your program, you used the exponent operator for exponential or power calculation on num variable
      In a while loop, your number gets incremented but inside your while loop, your num cannot be incremented. so that's why the num value still remain the old value, which is incremented in while loop
      So at the initialization or in while loop, the num is incremented by 1 but inside the while loop, the num is not incremented by 1
      ASP.Net Software Development

      Comment

      Working...
      X