[introduction to Python] Chapter 56 loop advanced while... else statement

Posted by darcuss on Sat, 19 Feb 2022 19:49:24 +0100

Chapter 18 This paper introduces the while loop statement in Python. This article discusses the else branch option of the while statement.

while else statement

The while statement in Python supports an optional else branch. The syntax is as follows:

while condition:
    # code block to run
else:
    # else clause code block

In the above syntax, condition will be detected at the beginning of each iteration. If the result is True, execute the code in the while statement. If the condition condition is False, the else branch will be executed. However, if the loop is terminated by a break or return statement, the else branch is not executed.

The flow chart of while... Demonstrates the execution process of the following statements:

Next, let's look at an example.

Example of while else statement

The following is a list of various fruits; Each fruit consists of a dictionary containing its name and quantity.

basket = [
    {'fruit': 'apple', 'qty': 20},
    {'fruit': 'banana', 'qty': 30},
    {'fruit': 'orange', 'qty': 10}
]

Now we need to write a program that allows users to enter a fruit name. The basket list is then searched based on this input, and if the corresponding fruit is found, its quantity is displayed. If the corresponding fruit is not found, the user is allowed to enter the quantity of the fruit and add it to the list.

For this purpose, we can write the following program:

basket = [
    {'fruit': 'apple', 'qty': 20},
    {'fruit': 'banana', 'qty': 30},
    {'fruit': 'orange', 'qty': 10}
]

fruit = input('Enter a fruit:')

index = 0
found_it = False

while index < len(basket):
    item = basket[index]
    # check the fruit name
    if item['fruit'] == fruit:
        found_it = True
        print(f"The basket has {item['qty']} {item['fruit']}(s)")
        break

    index += 1

if not found_it:
    qty = int(input(f'Enter the qty for {fruit}:'))
    basket.append({'fruit': fruit, 'qty': qty})
    print(basket)

The above code is not the best implementation, and is only used for demonstration here. Its execution process is as follows:

  • First, use the input() function to receive user input.
  • Secondly, initialize the subscript index to 0 and find_ The IT identity is initialized to False. The subscript index is used to access the basket list. found_ The IT flag will be set to True when the corresponding fruit is found.
  • Then, traverse the list and check whether the corresponding fruit name matches the input. If it matches, it will be found_ Set it to True to display the number of fruits and exit the cycle.
  • Finally, check found at the end of the cycle_ It id, if found_ If the it result is False, the new fruit will be added to the list.

When using apple as input, the running results are as follows:

Enter a fruit:apple
The basket has 20 apple(s)

When lemon is used as input, the operation results are as follows:

Enter a fruit:lemon
Enter the qty for lemon:15
[{'fruit': 'apple', 'qty': 20}, {'fruit': 'banana', 'qty': 30}, {'fruit': 'orange', 'qty': 10}, {'fruit': 'lemon', 'qty': 15}]

The program can run as expected, but it can be more concise if implemented with while else. For example:

basket = [
    {'fruit': 'apple', 'qty': 20},
    {'fruit': 'banana', 'qty': 30},
    {'fruit': 'orange', 'qty': 10}
]

fruit = input('Enter a fruit:')

index = 0

while index < len(basket):
    item = basket[index]
    # check the fruit name
    if item['fruit'] == fruit:
        print(f"The basket has {item['qty']} {item['fruit']}(s)")
        found_it = True
        break

    index += 1
else:
    qty = int(input(f'Enter the qty for {fruit}:'))
    basket.append({'fruit': fruit, 'qty': qty})
    print(basket)

The modified program does not need to use found_it identifies the if statement after the loop statement. If the corresponding fruit is not found, the while loop will normally terminate and execute else branch to add new fruit. If the corresponding fruit is found, the while loop will be terminated in advance through the break statement, and the else branch will not be executed at this time.

summary

  • If the loop check condition of the while else statement is False and the loop is not terminated by a break or return statement, the else branch will be executed.
  • If there are any identification variables in the while loop, you can try using the while else statement.

Topics: Python for while