Else in Python

Source: Internet
Author: User
This article mainly introduces the detailed details of else in Python. For more information, see if... elif... else ..., however, else has two other purposes: one is for the end of the loop and the other is for the try of error handling. This was originally the standard syntax of Python, but because it is not the same as most programming languages, people intentionally or unintentionally ignore these usage. In addition, there is a lot of controversy about whether these usage conforms to The 0 × 00 The Zen of Python principle and whether they should be widely used. For example, in the two books I have read (objective Python VS Write Idiomatic Python), the two authors have different attitudes towards them respectively.

Else in loop

The else statement following the loop is executed only when there is no break in the loop, that is, the normal loop is completed. First, let's look at an example of insert sorting:

from random import randrangedef 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, 100) for i in range(10)]))[8, 12, 12, 34, 38, 68, 72, 78, 84, 90]

In this example, the sorted _ sorted elements are compared with I one by one. if I is larger than all sorted elements, it can only be placed at the end of the sorted list. In this case, we need an additional state variable inserted to mark whether the traversal loop is completed or break is midway through. in this 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 _sortedprint(insertion_sort([randrange(1, 100) for i in range(10)]))[1, 10, 27, 32, 32, 43, 50, 55, 80, 94]

I think this is a very cool practice! However, note that in addition to the break, the following else statements can be triggered. when there is no loop:

while False:  print("Will never print!")else:  print("Loop failed!")Loop failed!

Else in error capture

Try... else t... else... the finally flow control syntax is used to capture possible exceptions and handle them accordingly. limit T is used to capture errors in try statements, while else is used to process errors without errors; finally is responsible for the "aftercare" of try statements, which can be executed in any case. A simple example is provided:

def pide(x, y):  try:    result = x / y  except ZeropisionError:    print("pision by 0!")  else:    print("result = {}".format(result))  finally:    print("pide finished!")pide(5,2)print("*"*20)pide(5,0)


result = 2.5pide finished!********************pision by 0!pide finished!

Of course, else can also be replaced by state variables:

def pide(x, y):  result = None  try:    result = x / y  except ZeropisionError:    print("pision by 0!")  if result is not None:    print("result = {}".format(result))  print("pide finished!") pide(5,2)print("*"*20)pide(5,0)


result = 2.5pide finished!********************pision by 0!pide finished!

Summary

Some people think that these else usage violates intuition or implicit, rather than explicit it, and is not worth advocating. However, I think this "decision" depends on the specific application scenario and our understanding of Python. it is not necessary to make a friendly syntax for new users to be explicit. Of course, this syntax is not recommended in all places, for/while... the biggest disadvantage of else is that else needs to be aligned with for/file. if it is nested in multiple layers or the loop body is too long, else is very unsuitable (recall the stem of the vernier caliper and you will know: P ). Only in some short loop control statements can we get rid of some cumbersome state variables through else. this is the most Pythonic application scenario!

For more details about else in Python, refer to PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.