• Python 中的循环与 else


    1. 含义

    Python 中的循环与 else 有以下两种形式

    • for … else
    • while … else

    Python中的 for、while 循环都有一个可选(optional)的 else 分支(类似 if语句和 try 语句那样),在循环迭代正常完成之后执行。

    所谓循环迭代正常完成,一般是指(所需要迭代处理的对象遍历完毕,且中间没有异常发生):

    • 没有执行 break
    • 没有执行 return
    • 循环的中间没有异常发生

    注:纵然有 continue 语句,循环也是正常完成的;

    In [1]: for i in range(5):
       ...:     if i & 1 == 0:
       ...:         continue
       ...:     print(i)
       ...: else:
       ...:     print('Iteratived over everything')
       ...:
    1
    3
    Iteratived over everything
    • 尽管循环所迭代的序列是空的,else分支依然会被执行,毕竟循环仍然是正常完成的。
    >>> for i in []:
    ...     print(i)
    ... else:
    ...     print('Still iterated over everything (i.e. nothing)')
    ...
    Still iterated over everything (i.e. nothing)

    2. 思考

    如此设计的意义何在呢?

    else 语句在循环中的一个常见使用案例是实现循环查找。假说你在查找一个满足特定条件的项目(item),同时需要进行附加处理,或者在未发现可接受的值时生成一个错误:

    for x in data:
        if meets_cond(x):
            break
        ...
    else:
        .... 

    没有 else 语句的话,你需要设置一个标志,然后在后面对其检测,以此确定是否存在满足条件的值。

    found = False
    for x in data:
        if meets_cond(x):
            found = True
    if not found:
        ...     

    Python中循环语句中的else用法

  • 相关阅读:
    passwd: Have exhausted maximum number of retries for service
    将单个文件上传到多机器工具
    leetcode-Jump game II
    LeetCode--Combination Sum --ZZ
    Leetcode- Find Minimum in Rotated Sorted Array-ZZ
    leetcode-permutation sequence
    leetcode-next permutation
    LeetCode-Subsets ZZ
    leetcode-Restore IP Addresses-ZZ
    leetcode-palindrome partitioning-ZZ
  • 原文地址:https://www.cnblogs.com/mtcnn/p/9424207.html
Copyright © 2020-2023  润新知