• Index

#### 循环

Last updated: ... / Reads: 500371611 Edit

### 循环

>>> 1 + 2 + 3
6

Python的循环有两种，一种是for...in循环，依次把list或tuple中的每个元素迭代出来，看例子：

names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)

Michael
Bob
Tracy

sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum = sum + x
print(sum)

>>> list(range(5))
[0, 1, 2, 3, 4]

range(101)就可以生成0-100的整数序列，计算如下：

# -*- coding: utf-8 -*-
----
sum = 0
for x in range(101):
sum = sum + x
print(sum)

sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)

### 练习

# -*- coding: utf-8 -*-
----

### break

n = 1
while n <= 100:
print(n)
n = n + 1
print('END')

n = 1
while n <= 100:
if n > 10: # 当n = 11时，条件满足，执行break语句
break # break语句会结束当前循环
print(n)
n = n + 1
print('END')

### continue

n = 0
while n < 10:
n = n + 1
print(n)

n = 0
while n < 10:
n = n + 1
if n % 2 == 0: # 如果n是偶数，执行continue语句
continue # continue语句会直接继续下一轮循环，后续的print()语句不会执行
print(n)

### 小结

break语句可以在循环过程中直接退出循环，而continue语句可以提前结束本轮循环，并直接开始下一轮循环。这两个语句通常都必须配合if语句使用。

do_for.py

do_while.py