python循环的使用
while循环
- 与C语言的类似,举个例子吧
i = 5
while i>0:
print('Hello,World')
i -= 1;
结果为
Hello,World
Hello,World
Hello,World
Hello,World
Hello,World
for循环
- Python的for循环比起C语言的更加智能,他的格式为
for 目标 in 可迭代对象:
循环体
- for example
s = 'Hello,World'
for i in s:
print(i,end=' ')
结果为
H e l l o , W o r l d
- i从s的开头开始,此时的i表示 s[i] 每次执行完i自动向后移动
- for循环其实相当于使用了迭代器
range()函数
- 它常与for循环搭配使用,他的格式为
range( [start=0 , ] stop [, step=1] )
中括号内表示可以缺省和缺省后的默认值,注意:如果输入两个参数,则这两个参数对应为strat和stop,而不是stop和step。步长可以为负,通常此时start>stop
- for example
for i in range(10,0,-2):
print(i,end=' ')
for i in range(3):
print(i,end=' ')
结果分别为
10 8 6 4 2
0 1 2
- 类似于MATLAB的0:2:10,但不同点在于range是可以取到start但取不到stop的,因此上面的两个代码不会输出0和3
break和continue
- 用法与C语言的相同,不再说明