How does the While loop exits in the below code?

def locate_card(cards, query):
# Create a variable position with the value 0
position = 0

# Set up a loop for repetition
while True:
    
    # Check if element at the current position matche the query
    if cards[position] == query:
        
        # Answer found! Return and exit..
        return position
    
    # Increment the position
    position += 1
    
    # Check if we have reached the end of the array
    if position == len(cards):
        
        # Number not found, return -1
        return -1

I suppose this is your code:

def locate_card(cards, query):
    # Create a variable position with the value 0
    position = 0

    # Set up a loop for repetition
    while True:
        # Check if element at the current position match the query
        if cards[position] == query:
            # Answer found! Return and exit..
            return position
        # Increment the position
        position += 1

        # Check if we have reached the end of the array
        if position == len(cards):
          # Number not found, return -1
            return -1       

Since, while loop is set to True, it means the loop will run infinitely unless it is set to break inside itself. It can be done either by using break inside loop for some condition, or as in this case, returning some value.

return statement when executed inside loop breaks the loop.

So, either the query will be found in cards list then the first if statement will be executed and returns the position of the query and it exits the loop or it will not be found in that case we check whether we searched all positions of the cards list (second if statement). If we have then we return -1 and it exits the loop.

Thanks. Return statement breaks the while loop is the key… I am a beginner to python…

2 Likes