We all know that the basic usage of else in Python is the if...elif...else in the conditional control statement ..., but else there are two other uses, one for the end of the loop and the other for the error-handling try. This was originally the standard syntax for Python, but because of the different habits of most other programming languages, people intentionally or unintentionally ignored these usages. In addition, there are many controversies as to whether these usages conform to 0x00 's principles of the Zen Python and should not be widely used. For example, in the two books I saw (effective Python VS Write idiomatic python), the two authors held a different attitude towards each of them. QandA. ren programming
else in a loop
The Else statement that follows the loop only executes when no break occurs within the loop, that is, when the normal loop is complete. First, let's take a look at an example of inserting a sort method:
From random import Randrange
def insertion_sort (seq):
If Len (SEQ) 1:
return seq
_sorted = Seq[:1]
For i in Seq[1:]:
inserted = False
For j in Range (Len (_sorted)):
If I _sorted[j]:
_sorted = [*_sorted[:j], I, *_sorted[j:]]
inserted = True
Break
If not inserted:
_sorted.append (i)
Return _sorted
Print (Insertion_sort ([Randrange (1) for I in range (10)]))
[8, 12, 12, 34, 38, 68, 72, 78, 84, 90]
In this example, the sorted _sorted elements are compared to I, and if I is larger than all the ordered elements, it can only be ranked at the end of the sorted list. At this point we need an extra state variable inserted to mark the completion of the traversal loop or break in the middle, in which case we can replace this state variable with else:
def insertion_sort (seq):
If Len (SEQ) 1:
return seq
_sorted = Seq[:1]
For i in Seq[1:]:
For j in Range (Len (_sorted)):
If I _sorted[j]:
_sorted = [*_sorted[:j], I, *_sorted[j:]]
Break
Else
_sorted.append (i)
Return _sorted
Print (Insertion_sort ([Randrange (1) for I in range (10)]))
[1, 10, 27, 32, 32, 43, 50, 55, 80, 94]
I think it's a really cool way to do it! However, it is important to note that, except that break can trigger the subsequent else statement, there is no loop:
While False:
Print ("would never print!")
Else
Print ("Loop failed!")
Loop failed!
else in error capture
The try...except...else...finally Process Control syntax is used to catch possible exceptions and handle them appropriately, where except is used to catch errors that occur in a try statement, while else is used to handle situations where there are no errors; finally is responsible for The "Aftermath" of the Try statement is executed anyway. This can be demonstrated by a simple example:
def divide (x, y):
Try
result = X/y
Except Zerodivisionerror:
Print ("Division by 0!")
Else
Print ("result = {}". Format (Result))
Finally
Print ("Divide finished!")
Divide (5,2)
Print ("*" *20)
Divide (5,0)
result = 2.5
Divide finished!
********************
Division by 0!
Divide finished!
Of course, you can also replace the else with the state variable approach:
def divide (x, y):
result = None
Try
result = X/y
Except Zerodivisionerror:
Print ("Division by 0!")
If result is not None:
Print ("result = {}". Format (Result))
Print ("Divide finished!")
Divide (5,2)
Print ("*" *20)
Divide (5,0)
result = 2.5
Divide finished!
********************
Division by 0!
Divide finished!
Summarize
Some people think that the use of else is counterintuitive or implicit rather than explicit, and it is not worth advocating. But I think that this "verdict" relies on specific application scenarios and our understanding of Python, not necessarily the new friendly grammar is explicit. Of course, it is not recommended to use this syntax in all places, the biggest disadvantage of For/while...else is that else is required to be aligned with for/file, if it is a multi-layered nesting or the loop body is too long, it is very ill-suited to the other (recall the stem of the vernier caliper will know: P). Only in some short loop control statements, we get rid of some cumbersome state variables through else, this is the most pythonic application scenario!
The else in Python describes. For example, the code