Python小知识:else除了跟if很搭,你还知道其他的关键词吗?
2018-03-15 20:44
309 查看
用Python这么久了,只知道else与if很搭,其实跟else关系很好的关键词还有while、for。
一、while
1.1 最基本的while循环
while condition: statements只要condition条件是True,程序就执行while代码块中的statements。例如:
restrict = 5 index = 1 while index<restrict: print('{}<{}'.format(index,restrict)) index+=1
1<5 2<5 3<5 4<5
1.2 带else的while循环
大家都知道if_else,我一直以为python的世界里只有if才和else很配,没想到while也可以这么写。貌似很少看到这种写法while conditon: statement1 else: statement2例如
restrict = 5 index = 1 while index<restrict: print('{}<{}'.format(index,restrict)) index+=1
else:
print('程序结束')
1<5 2<5 3<5 4<5需要注意一点,当while中break之后,else里的指令就不会再执行。
程序结束
二、for循环
2.1 最简单的for
for item in iterable_obj: statements
2.2 for_else
真没想到,if、while和for都能跟else搭配使用!for item in iterable_obj: statement1 else: statement2例如
fruits = ["banana", "apple", "orange", "kiwi"] for food in fruits: print(food) else: print("reached end of list")
banana apple orange kiwi reached end of list
相关文章推荐
- python-基础知识之if...else...
- CI框架中if else 重点的冒号位置基础知识
- 2.8 python中的if...elif...else语句 [python入门教程]
- Python新手学习基础之条件语句——if/else语句
- 零基础学python-11.5 真值测试与if...else...三元表达式
- Python学习第三章《变量》(成为高手前必须知道的一些基础知识)
- Python-if-elif-else语句
- Python3.4入门之ifelse错误解决方案
- Python 初体验之 最基本的if-else-while-for
- Python的 if .else.elif语句详解
- python之路-day1-if...else...流程判断
- 【脚本语言系列】关于Python基础知识魔法变量,你需要知道的事
- python学习:if...else
- python基础语法之if,else,for,while,continue,break
- python -- 02 流程控制(1)if else
- Python第一弹 使用if-elif-else
- Python学习第三章《字符串》(成为高手前必须知道的一些基础知识)
- 【脚本语言系列】关于Python基础知识对象变动,你知道的事
- Python中如何避免使用多个分支语句(多个if和else)——函数字典(Function Map)简介
- 【Python入门】9、if、elif、else,if的嵌套