pythonwhile-loopoperationconvergence

AND OR on python


The code below works such that an array is an input in a function. This 2 element array is iterated such that it would stop if the difference between the new and previously iterated array values equals zero (or it is intended to work as such). Note that the function below is just a pseudo function.

Is using a "OR" and "AND" operator appropriate for what I want. If so, which is best to use and if not, what is a better method?

def func(array):
   
   counter = 0
   diff = True 
   array_i = array
   while diff: 
       array_f = array_i + 1/array_i
       diff = abs(array_i[0] - array_f[0])  or abs(array_i[1] - array_f[1]) > 0 
       array i = array_f 
       counter += 1
   return array_i, counter 

Solution

  • The logical operator or is used when you want to check a condition or another condition. The and operator is when both are to be combined.

    Checks to see if either one or the other are greater than zero.

    abs(array_i[0] - array_f[0]) > 0 or abs(array_i[1] - array_f[1]) > 0 
    

    checks to see if both are greater than zero.

    abs(array_i[0] - array_f[0]) > 0 and abs(array_i[1] - array_f[1]) > 0