Home > Back-end >  Why does while loop not repeat in python
Why does while loop not repeat in python

Time:02-28

I am writing a code to print a table for the square root. But it doesn't loop. I need it to loop.

import math
                
def test_sqrt():
    a = 1
    def my_sqrt(a):
        while True:
            x = 1
            y = (x   a/x) / 2.0
            if y == x:
                return y

    while(a < 26):
        print('a = '   str(a)   ' | my_sqrt(a) = '   str(my_sqrt(a))   ' | math.sqrt(a) = '   str(math.sqrt(a))   ' | diff = '   str(my_sqrt(a) - math.sqrt(a)))
        a = a   1
        

test_sqrt()

CodePudding user response:

Reason is that python is going into infinite loop when a=2. This can be checked via debugger.

CodePudding user response:

Cause you built an infinite while-loop in your my_sqrt(a) function:

def my_sqrt(a):
    while True:
        x = 1
        y = (x   a/x) / 2.0
        if y == x:
            return y

With the second run you have y != x (unequal), hence there is no changing in y or x within the infinite loop, the loop will never break by reaching the return y.

By this, the loop:

while(a < 26):
    print('a = '   str(a)   ' | my_sqrt(a) = '   str(my_sqrt(a))   ' | math.sqrt(a) = '   str(math.sqrt(a))   ' | diff = '   str(my_sqrt(a) - math.sqrt(a)))
    a = a   1

runs once an then gets stuck on the second iteration of the my_sqrt(a) function when a = 2.

CodePudding user response:

You are stuck in an endless loop when a = 2 and you call my_sqrt(2):

my_sqrt(2):
    x = 1
    y = (x   a/x) / 2.0 = 1.5

Since all of the variables x, a and y are constant in that context, the if y == x: condition is never used. So you stay stuck in the while True: loop forever.

CodePudding user response:

You're almost there:

import math
            
def test_sqrt():
    a = 1
    err = 1e-6

    def my_sqrt(a):
        x=1
        while True:
            y = (x   a/x) / 2.0

            if abs(y-x)<err:
                return y
        
            x = y

    while(a < 26):
         print('a = '   str(a)   ' | my_sqrt(a) = '   str(my_sqrt(a))   ' | math.sqrt(a) = '   str(math.sqrt(a))   ' | diff = '   str(my_sqrt(a) - math.sqrt(a)))
        a = a   1
    

 test_sqrt()

Notes:

  1. The value of x is defined at the beginning, not each loop
  2. The value of x needs to be updated each loop, if we haven't returned from the function
  3. The computation is continued until it is close enough, absolute difference is less than err
  • Related