Python有两种循环结构:while
和 for...in...
while
while
当其后的判断条件满足时,就是执行缩进的语句块,直到while
后面的条件不满足就停止。语法格式:
- while 判断条件:
- 语句块
Python
例如求和1+2+3+4+5:
- n = 1
- sum = 0
- while n<=5:
- sum = sum+n
- print(sum)
Python
将上述代码写入while.py文件中,执行命令python3 while.py
,输出结果为15.
for…in…
for x in seq
就是把seq的每个迭代元素代入变量x,然后依次执行缩进的语句块。语法格式:
- for var in sequence:
- 语句块
Python
例如求阶乘5!:
- n = 5
- result = 1
- for x in [1,2,3,4,5]:
- result = result * x
- print(result)
Python
将上述代码写入for.py文件中,执行命令python3 for.py
,输出结果为120.
break & continue
提前跳出循环有两种语法:break
和continue
。两者区别在于:break
是跳出整个循环,而continue
是跳出当前循环。例如:
- list = ['a','b','c','d','e']
- for x in list:
- if x!='c':
- print(x)
- else :
- break
Python
输出如下:
a
b
如果将break
换成continue
,则输出如下:
a
b
d
e