1.while循环
while循环的语句格式为:
while condition)
statements
当判断条件为真时,就会执行循环中的语句,当条件为假时退出循环,若条件为一个永真式,那么将会无限循环。
例如:
count = 0
while (count < 9):
print('The count is:', count)
count = count + 1
print("Good bye!")
结果为:
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
循环执行了9次,第十次count=9,不满足条件,退出循环,打印输出。
除此之外,while还可以嵌套else使用,如:
count = 0
while (count < 9):
print('The count is:', count)
count = count + 1
else:
print("Good bye!")
输出的结果与上方一样,只是它进入了else语句块。
2.for循环
for循环的语句格式为:
for iterating_var in sequence:
statements(s)
与c,java这些for循环不同,python的for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
例如:
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print('当前水果 :', fruits[index])
print("Good bye!")
输出:
当前水果 : banana
当前水果 : apple
当前水果 : mango
Good bye!
同样,for循环也支持else嵌套,多重for嵌套
如冒泡排序
arays = [11,38,22,16,13,59,24]
for i in range(len(arays)):
for j in range(i+1):
if arays[i] < arays[j]:
# 实现连个变量的互换
arays[i],arays[j] = arays[j],arays[i]
print(arays)
[11, 13, 16, 22, 24, 38, 59]
3. break语句
- Python break语句,就像在C语言中,打破了最小封闭for或while循环。
- break语句用来终止循环语句,即循环条件没有False条件或者序列还没被完全递归完,也会停止执行循环语句。
- break语句用在while和for循环中。
- 如果使用嵌套循环,break语句将停止执行最深层的循环,并开始执行下一行代码。
以上面的冒泡排序为例:
arays = [11,38,22,16,13,59,24]
for i in range(len(arays)):
for j in range(i+1):
if arays[i] < arays[j]:
if j == 3:
break
arays[i],arays[j] = arays[j],arays[i]
print(arays)
输出
[11, 13, 16, 38, 22, 59, 24]
可见在j=3时就停止了排序,终止循环。
4.continue语句
continue与 berak的区别是,continue跳出本次循环,而break跳出整个循环。
continue 语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。
continue语句用在while和for循环中。
例如:
for i in range(6):
if i==4:
continue
print(i,end=" ")
输出:
0 1 2 3 5
当i=4时终止本层循环,跳到下一层循环,因此4没有输出。
另外有个pass语句,pass 是空语句,是为了保持程序结构的完整性。pass 不做任何事情,一般用做占位语句。我感觉这个是强迫患者的福音,哈哈哈。