Can a function be used in a while expression?



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


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