Python for...else
来源:互联网 发布:主提女装淘宝店有吗 编辑:程序博客网 时间:2024/05/21 06:13
Python中的一个特殊语法,如果循环执行过程中没有break则执行else
一个例子如下:
for item in container: if search_something(item): # Found it! process(item) breakelse: # Didn't find anything.. not_found_in_container()
可以发现这个操作主要是用在之前需要flag的情况下。比如输入一个数,在列表中进行匹配。
我们可以这么写
#!/usr/bin/pythonto_match = int(raw_input("Enter number:"))num_list = [1, 2, 3, 4]found_match = Falsefor idx, num in enumerate(num_list): if num == to_match: print "{} matches at Position {}".format(num, idx) found_match = True breakif not found_match: print "No match found"
了解到for...else...
的功能之后我们就可以改成
to_match = int(raw_input("Enter number:"))num_list = [1, 2, 3, 4]for idx, num in enumerate(num_list): if num == to_match: print "{} matches at Position {}".format(num, idx) breakelse: print "No match found"
阅读全文
0 0
- python -- for...else
- python for else
- python中的for...else...
- Python for else笔记
- python for else primers
- python for else 循环
- Python for...else
- python学习:for else语句
- Python 中的for-else用法
- Python for循环和else
- Python的for…else和while…else语法
- python中的for...else的使用方法
- python 基本语法 if else for
- python中for和else学习
- for...else...
- Python: while和for循环可增加else从句
- Python for, while循环后面加else的作用
- python中for/else组合实现素数的输出
- [HDU](2544)最短路 ---单源最短路径(图)
- 漫谈程序员系列:怎么告别“混日子”
- 对反向传播算法的理解
- sqlite_exec回调函数的使用
- 一 ServletContext 和 spring ClassPathXmlApplicationContext
- Python for...else
- 最长不下降子序列
- Qt之QWidget/QDialog/QMainWindow
- 概念 Qt
- 工具类—Java下载远程文件到本地
- LeetCode-110-Balanced Binary Tree(平衡二叉树)
- CBC模式的DES加密算法(加密字符串、加密文件)
- 四、用简单神经网络识别手写数字(内含代码详解及订正)
- WEB前端开发之ES6(1)