Home > Mobile >  Python while loop basics, check order of the list
Python while loop basics, check order of the list

Time:01-31

I want to check if element in list is smaller than the next one and break function in a moment when it is not. I have written this code and I am not sure what is wrong because output is [1] when it should be [1, 3, 4, 5, 6, 7]. It is probably small error, but I have none to ask..

def check_order(a):
  i = 0
  while i < (len(a)-1):
    b = []
    if a[i] < a[(i   1)]:
        b.insert(i, a[i])
        i = i   1
        return b
    else:
        break

    
a = [1, 3, 4, 5, 6, 7, 22, 10]

print(check_order(a))

CodePudding user response:

There are 2 issues, you are redefining b on every loop, and also returning early inside the if statement

def check_order(a):
    i = 0
    b = []
    while i < (len(a) - 1):
        if a[i] < a[(i   1)]:
            b.insert(i, a[i])
            i = i   1
        else:
            break
    return b

CodePudding user response:

I think you need to understand what will happen return statement is called.

when you call the return statement the flow will return to the function calling the place

enter image description here

So during the first loop it self when it comes 8th line control will come back to 11th line . So output is only 1

so you can change something like below

def check_order(a):
    i = 0
    b = []
    while i < (len(a) - 1):
        if a[i] < a[(i   1)]:
            b.insert(i, a[i])
            i = i   1
        else:
            break
    return b

a = [1, 3, 4, 5, 6, 7, 22, 10]

print(check_order(a))

Here we have return at end of while loop , So the control from return will come to function call at end of while loop

  •  Tags:  
  • Related