条件控制
- 用法
if 条件1:
执行语句
elif 条件2:
执行语句
...
else:
执行语句
2.Python不仅仅可以使用布尔型变量作为条件,它可以直接在if中使用任何表达式作为条件:
大部分表达式的值都会被当作True,但以下表达式值会被当作False:
- False
- None
- 0
- 空字符串,空列表,空字典,空集合
循环
while 循环
用法:
while <condition>:
<statesments>
Python会循环执行,直到不满足为止。
空容器会被当成 False ,因此可以用 while 循环来读取容器中的所有元素
plays = set(['Hamlet', 'Macbeth', 'King Lear'])
while plays:
play = plays.pop()
print 'Perform', play
*运行结果*
Perform King Lear
Perform Macbeth
Perform Hamlet
for …in 循环
for <variable> in <sequence>:
<indented block of code>
for 循环会遍历完中所有元素为止
continue 语句
遇到 continue 的时候,程序会返回到循环的最开始重新执行。
values = [7, 6, 4, 7, 19, 2, 1]
for i in values:
if i % 2 != 0:
# 忽略奇数
continue
print i/2
*运行结果*
3
2
1
break 语句
遇到 break 的时候,程序会提前结束循环
n=1
while n<=100:
if n>10:
break
print(n)
n=n+1
*运行结果*
1
2
3
4
5
6
7
8
9
10
http://lijin-thu.github.io/02.%20python%20essentials/02.15%20loops.html