跳到主要内容

循环

循环

for循环

# for 循环
total = 0
for i in range(100000):
total += i
print(total) # 4999950000

while 循环

while <condition>:
<statesments>

Python会循环执行statesments,直到condition不满足为止。

i = 0
total = 0
while i <= 100:
total += i
i += 1
print(total) # 5050

举个例子,通过while遍历集合:

# 空容器会被当成False,因此可以用while循环读取容器的所有元素
plays = set(['Hamlet', 'Mac', 'King'])
while plays:
play = plays.pop()
print('Perform', play)

continue 语句

遇到 continue 的时候,程序会返回到循环的最开始重新执行。

values = [7, 6, 4, 7, 19, 2, 1]
for i in values:
if i % 2 != 0:
# 忽略奇数
continue
print(i)
# 6
# 4
# 2

break 语句

遇到 break 的时候,程序会跳出循环,不管循环条件是不是满足

command_list = ['start',
'1',
'2',
'3',
'4',
'stop',
'restart',
'5',
'6']
while command_list:
command = command_list.pop(0)
if command == 'stop':
break
print(command)
# start
# 1
# 2
# 3
# 4