流程控制 #
条件控制 #
if #
if x > y:
print('x > y')
print('end')
elif x < y:
print('x < y')
else:
print('x == y')
print('end')
循环控制 #
For #
For 语句
nums = [1, 2, 3, 4, 5]
for n in nums:
print('for-in', str(n))
也可以通过 Range 对象实现基于索引的循环,左开右闭
for n in range(1, 10, 3):
print('for-range', str(n)) # 1 4 7
For 推导式
a = [i for i in range(100) if not (i % 2) and i % 3]
print(a) # [2, 4, 8, 10, 14,...
b = {i: i % 2 == 0 for i in range(10)}
print(b) # {0: True, 1: False, 2: True, 3: False, 4: True,...
While #
Python 的 while
语句可以附带 else
i = 0
while i < 3:
print('while', str(i))
i += 1
else:
print('end while', str(i))
Break 和 Pass #
Break 用于终止循环,Pass 用于进入下次循环
Break
for i in range(1, 5):
if i == 3:
break
print('break', str(i))
Pass
for i in range(1, 5):
if i == 3:
pass
print('next', str(i))