你所不知道的python循环中的else

众多语言中都有if else这对条件选择组合,但是在python中还有更多else使用的地方,比如说循环for,或者while都可以和else组合。

下面简单介绍一下for-else while-else组合

循环组合中的else执行的情况下是循环正常结束(即不是使用break退出)。如下列代码:

numbers= [1,2,3,4,5]
for nin numbers:
    if (n >5):
        print('the value is %d '%(n))
        break
else:
    print('the for loop does not end with break')
     
i= 0
while(numbers[i] <5):
    print('the index %d value is %d'%(i, numbers[i]))
    if (numbers[i] <0) :
        break
    i= i+ 1
else:
    print('the loop does not end with break')
   
numbers= [1,2,3,4,5]
for nin numbers:
    if (n >5):
        print('the value is %d '%(n))
        break
else:
    print('the for loop does not end with break')
    
i= 0
while(numbers[i] <5):
    print('the index %d value is %d'%(i, numbers[i]))
    if (numbers[i] <0) :
        break
    i= i+ 1
else:
    print('the loop does not end with break')

执行结果如下:

C:\Python27>python.exe for_else.py
thefor loop doesnot end withbreak
the index0 valueis 1
the index1 valueis 2
the index2 valueis 3
the index3 valueis 4
the loop doesnot end withbreak

相关推荐

  1. CSS那些知道选择器

    2024-03-24 02:50:02       22 阅读
  2. PythonMap函数:简化循环和函数调用

    2024-03-24 02:50:02       17 阅读
  3. Python循环语句

    2024-03-24 02:50:02       24 阅读
  4. 知道CSS函数:attr() 深度探索

    2024-03-24 02:50:02       12 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-24 02:50:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-24 02:50:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-24 02:50:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-24 02:50:02       18 阅读

热门阅读

  1. 计算机二级考试注意事项(Python程序设计篇)

    2024-03-24 02:50:02       18 阅读
  2. perl:获取同花顺数据--业绩预告

    2024-03-24 02:50:02       20 阅读
  3. Hive在虚拟机中的部署

    2024-03-24 02:50:02       18 阅读
  4. C++语句,空语句,复合语句

    2024-03-24 02:50:02       19 阅读
  5. SQL题:

    SQL题:

    2024-03-24 02:50:02      16 阅读
  6. Python 类的学习

    2024-03-24 02:50:02       16 阅读
  7. 洛谷 P1011 [NOIP1998 提高组] 车站

    2024-03-24 02:50:02       17 阅读
  8. kafka 01

    kafka 01

    2024-03-24 02:50:02      16 阅读