Python 控制语句

Python documentation - Control Flow

条件

注意

  • False、None、0、空字符串、()、[]和{}是False其他都是True
  • ==表示值相等,is表示是否是同一个对象
  • 短路逻辑 and和or

使用bool判断值

1
2
3
4
5
bool(1)
> True

bool(0)
> False

if else elif语句

1
2
3
4
5
6
if num >= 90:
print('优秀')
elif num >= 60:
print('及格')
else:
print('不及格')

断言

1
assert age > 0, 'illegal value'

循环

while循环

1
2
3
4
5
# Fibonacci sequence
a, b = 0, 1
while a < 1000:
print(a)
a, b = b, a+b

for循环

1
2
3
4
5
6
7
8
9
10
11
12
# Array
for fruit in ['apple', 'banana', 'mango']:
print(fruit)

## Range
for i in range(2, 10):
print(i)

## Dict
coordinate = {'x': 20, 'y': 8, 'z': 16}
for key in coordinate:
print(coordinate[key])

跳出循环

1
2
break
continue

List comprehension

1
[(x, y) for x in range(5) for y in range(3)]