Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Dec 2017
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question 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. #2
    New Coder
    Join Date
    Jul 2013
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts
    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 "+=".


 

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •