Introduction to python Learn about the Special Features of for else

  • 2021-12-13 08:46:28
  • OfStack

Basic knowledge of the catalog For-Else feature 3 scenarios using the For-Else feature 1. Iterate and find items without flag variables 2. Help break nested loops 3. Help handle exception summaries

No matter what programming language we use, we will write "if-else" statements, but what about "for-else"?

For many languages, such as c, c + +, and Java, it is completely wrong to use "else" after the loop. However, as an elegant language, Python has this strange but useful feature. If we use it correctly, our code will become cleaner.

Basic knowledge of For-Else features

When Python developers first encountered the "for-else" feature, it looked strange and difficult to understand. But in fact, its usage is surprisingly simple. One sentence is enough to explain this problem: the "else" block is executed only when there is no interruption in the loop.

Too simple to be true? Let's use an example to test 1:


leaders = ["Elon", "Tim", "Warren"]
for i in leaders:
    if i == "Yang":
        print("Yang is a leader!")
        break
else:
    print("Not found Yang!")
# Not found Yang!

As shown above, the list leaders does not contain "Yang", so there is no interruption in the for loop. Therefore, the "else" block executes and prints the information.

What happens if "Yang" is included in the list leaders?


leaders = ["Yang", "Elon", "Tim", "Warren"]
for i in leaders:
    if i == "Yang":
        print("Yang is a leader!")
        break
else:
    print("Not found Yang!")
# Yang is a leader!

As shown above, since "Yang" is in the leaders list, the for loop is broken and the "else" block is not executed.

In short, the for-else feature is not difficult to understand, but it is not easy to use it correctly and skillfully.

Three scenarios using For-Else features

We don't have to use the for-else feature in the Python program. To be honest, we can do the same without it, but using it can make our code more elegant.

1. Iterate and find items without flag variables

Finding specific items by iterating through lists is the basic scheme of using loops. Usually, when we find the project, it is meaningless to continue iteration, we need to break the loop. The question is: How do we know if this item has been found?

The traditional solution is to define an "flag" variable and set it to True when a specific item is found.


leaders = ["Yang", "Elon", "Tim", "Warren"]
have_yang = False
for i in leaders:
    if i == "Yang":
        have_yang = True
        # Do something
        break
if have_yang == False: # no yang
    ...  # Do others

This method is good enough, but if you want to make full use of the advantages of Python. Using the for-else feature is another option:


leaders = ["Yang", "Elon", "Tim", "Warren"]
for i in leaders:
    if i == "Yang":
        have_yang = True
        # Do something
        break
else:  # no yang
    ...  # Do others

Simpler and more convenient ~

2. Help break nested loops

The for-else feature also helps when nested loops exist.


for i in range(5):
    for j in range(5):
        if j == 2 and i == 0:
            break
    if not (j == 2 and i == 0):
        continue
    break 

As shown above, breaking nested loops is a little difficult, because we must know whether the inner loops are broken.

The above code shows a clumsy solution to determine whether the internal loop has been broken. It certainly works, but we can make it cleaner with the for-else feature:


# use the for-else syntax
for i in range(5):
    for j in range(5):
        if j == 2 and i == 0:
            break
    else:  # only execute when it's no break in the inner loop
        continue
    break

3. Help with exception handling

Exception handling is very important for programming and can be helpful if we use the for-else feature properly. For example:


nums = [1, 3, 0, 5]
for denominator in nums:
    try:
        20/denominator
    except ZeroDivisionError:
        break
else:  # no found ZeroDivisionError
    ...  # Do others

As shown above, if there is no ZeroDivisionError in the for loop, we can perform the corresponding operation in the "else" block.

Summarize

The for-else feature in Python looks strange at first. But this is not difficult to understand, and it is very useful in some cases. After all, we only need to remember the one-sentence rule: the "else" block is executed only if there is no interruption in the loop.

Above is python beginners about for else special features explain the details, more about python for else special features of information please pay attention to other related articles on this site!


Related articles: