Home > Article > Backend Development > For-else: A strange but useful feature in Python
No matter which programming language we use, we all write "if-else" statements, but what about "for-else"?
For many languages, such as C, C and Java, using "else" after a loop is completely wrong. However, Python, as an elegant language, has this "strange but useful" feature. If used correctly, our code will become cleaner.
This article will introduce the "for-else" function in Python and explain how to use it correctly through simple examples.
When you first encounter the "for-else" feature, it will look strange and It is difficult to understand (when you first started using this function, it was easy to mistakenly think that else was indented wrong). But in fact, its usage is surprisingly simple. One sentence will suffice: the "else" blocks in your code are only executed when there are no breaks in the loop.
Sound a bit too simple to be true? Let's take a look at an example:
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: As shown above, the leaders list does not contain "Yang", so there is no break in our for loop. So the "else" block executes and prints the information.
What if the leaders list contains "Yang"?
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, because the leaders list contains "Yang", the for loop is interrupted and the content in the "else" block is not executed.
In short, the for-else feature itself is not difficult to understand, but using it correctly and skillfully is not. Below we introduce three scenarios where the for-else feature is suitable.
We do not necessarily have to use the for-else feature in Python programs. Honestly, we can do the same thing without it, but using it makes our code more elegant.
Iterating through a list to find specific elements is the basic scenario for using loops. Usually when we find the target element, it makes no sense to continue iterating and we need to break out of the loop. The question is: how do we know if the element is found?
The traditional solution is to define a "mark" variable and set it to True when we find a specific item.
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
As shown in the above example, the have_yang variable is a flag. After the for loop completes, if its value is False, we know that "Yang" is not in the list and can do some other operations.
This method is good enough, but if you want to take advantage of Python's "elegant" features, using for-else 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
This way of writing looks like It looks neater, right?
For-else can also help when there are nested loops in the code.
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 out of nested loops is a little difficult because we have to know whether the inner loop is broken out.
The code above shows a clumsy solution to determine whether the inner loop has been interrupted. It certainly works fine, but we can make it neater by using for-else:
# 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
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 in the for loop No ZeroDivisionError occurs and we can perform the corresponding subsequent operations in the "else" block.
The for-else feature in Python may seem a little strange at first, but its usage is not difficult to understand and can be used in certain scenarios. its usefulness. After all, we only have to remember one rule: the "else" block is only executed when there are no breaks in the loop.
The above is the detailed content of For-else: A strange but useful feature in Python. For more information, please follow other related articles on the PHP Chinese website!