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

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

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

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

numbers = [1,2,3,4,5]   for n in 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 n in 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   the for loop does not end with break  the index 0 value is 1  the index 1 value is 2  the index 2 value is 3  the index 3 value is 4  the loop does not end with break

  • 初学者学习python2还是python3?
  • python获取本机IP、mac地址、计算机名
  • 详解python2 和 python3的区别
  • python基础之删除文件及删除目录的方法
  • 用python求第1000个质数的值
  • python常用函数年初大总结
  • Python3 - 时间处理与定时任务
  • Python开发的CMS系统,Silva CMS 3 发布
  • python基础之使用os.system来执行系统命令
  • 判断python字典中key是否存在的两种方法
  • 初学者学习python2还是python3?
  • python基础之删除文件及删除目录的方法
  • python获取本机IP、mac地址、计算机名
  • python获取系统时间(时间函数详解)
  • 详解python2 和 python3的区别
  • 用python求第1000个质数的值
  • Python3 - 时间处理与定时任务
  • 命令行看糗百
  • Python算法之---冒泡,选择,插入排序算法
  • python 中求和函数 sum详解
  • range方法在Python2和Python3中的不同
  • python3 数组(列表)初始化
  • 记一次crontab中date命令错用导致的问题
  • MySQL用LIKE特殊字符搜索
  • CentOS 7 下修改主机名
  • Python3正则表达式之:(?(id/name)y...
  • TIOBE编程语言排行榜2019年 Python稳居前三
  • 解压命令unzip常用方法汇总
  • 解析redis备份文件rdb的两种方法及对比
  • 百度视觉语义化平台2.0:交互升级和...
  • 5G时代的视觉语义化技术:软硬结合...
  • 百度AutoDL重磅升级至3.0:设计、迁...