Can a function be used in a while expression?

Question

When creating the expression to control a while loop, is it possible to use a function instead of just variables?

Answer

Yes, you can use a function call in the while expression. If calling only a function in the expression, it should return True or False. If the function is part of a more complex expression, then the end result of the expression should evaluate to True or False.

The following example shows a while loop using a function to check a variable being incremented inside the while loop.

def control_loop(val):
    # Return False if val exceeds limit of 10
    if val >= 10:
        return False
    return True


limit = 1
while control_loop(limit):
    limit += 1
    print(limit)
12 Likes

In order to understand it better, i copied/pasted the above example and the checked the result. The output was the list: [2,3,4,5,6,7,8,9,10]
As the condition in the main body of the function was
if val >= 10 (not just > ) return False , why is 10 included in the list?
I suppose that the answer is somehow hidden in the condition of the while loop, limit +=1. Nevertheless, I am not able to specify the final connection between these two conditions. In the beginning, I thought that limit +=1 is used only to ensure the incrementation one by one in the final list.
However, now it seems to me that the loop’s condition limit +=1 , “transforms” the function’s condition from val >=10 to val>=11.
Could you explain it a little bit more?

1 Like

Yes, and it has nothing to do with the fact that a function is involved in the control loop.

Let’s say that limit is up to 9, and control is at the while expression:

while control_loop(limit):  # argument control_group(limit) returns True: loop is entered
    limit += 1  #  limit is now 10
    print(limit)   # 10 is printed to the console

Now, back to while, this time with limit == 10:

while control_loop(limit):  # argument control_group(limit) now  returns False: loop is bypassed
    limit += 1  #  not executed
    print(limit)   # not executed
# loop terminates

Bottom line: It makes a difference where in the while() loop the index augmentation expression is placed. This is always the case. If you want the list to end with 9, just reverse the order of the augmentation and the print() expressions. (As you point out, you could also change the condition on val; it would have to be if val > 8:.)

1 Like

In order to obtain the same result displayed in lesson:

def control_loop(val): # Return False if val exceeds limit of 0 if val < 0: return False return True limit = 10 while control_loop(limit): print(limit) limit -= 1 print("We have liftoff!")
4 Likes