天天看点

while循环和for循环

一、while循环

1、while 循环,只要条件为真,我们就可以执行一组语句。

2、while 循环需要预先设置索引变量,并且需要编写代码执行索引变量+1。如下:我们需要定义一个变量 i,初始值设置为 1。

i = 1
while i < 7:
  print(i)
  i += 1
           

3、break 语句

如果使用 break 语句,即使 while 条件为真,我们也可以停止循环:

i = 0
while i < 7:
  i += 1
  if i == 3:
     break
  print(i)
           

输出:

1

2

3

4、continue 语句

如果使用 continue 语句,我们可以停止循环中的当前迭代,并继续下一个

i = 0
while i < 7:
  i += 1
  if i == 3:
     continue
  print(i)
           

输出:

1

2

4

5

6

7

二、for循环

1、for 循环用于迭代序列(即列表,元组,字典,集合或字符串)。通过使用 for 循环,我们可以为序列(即列表,元组,字典,集合或字符串)中的每个项目等执行一组语句。

2、for 循环不需要预先设置索引变量,索引变量自动+1。如下:

for x in "banana":
  print(x)
           

3、for循环一般和range() 函数结合使用

range() 函数默认从 0 开始,并递增 1(默认1,可以通过添加第三个参数来指定增量值,非必填),并以指定的数字结束。

4、for嵌套循环

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
  for y in fruits:
    print(x, y)
           

5、pass 语句

for 语句不能为空,如果因为某种原因写了无内容的 for 语句,可使用 pass 语句来避免错误

for x in [0, 1, 2]:
  pass
           

6、break 语句

通过使用 break 语句,我们可以在循环遍历所有之前停止循环

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    break
  print(x)
           

输出:

apple

7、continue 语句

通过使用 continue 语句,我们可以停止循环的当前迭代,并继续下一个

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)
           

输出:

apple

cherry