📜  循环 - Python (1)

📅  最后修改于: 2023-12-03 15:39:33.503000             🧑  作者: Mango

循环 - Python

1. for循环

for循环可以遍历任何序列(列表、元组、字符串等)中的每个元素,并在每个元素上执行相同的操作,适用于已知循环次数的情况。

# 遍历列表
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

# 遍历字符串
for x in "banana":
  print(x)

输出结果:

apple
banana
cherry

b
a
n
a
n
a
2. while循环

while循环用于重复执行一段代码,直到指定条件不成立为止,适用于未知循环次数的情况。

# 计数器实现while循环
i = 1
while i < 6:
  print(i)
  i += 1

# break语句跳出循环
i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1

# continue跳过此次循环
i = 0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)

输出结果:

1
2
3
4
5

1
2
3

1
2
4
5
6
3. 嵌套循环

嵌套循环可以在for循环或while循环内部使用另一个循环,适用于处理复杂问题。

# 乘法口诀表
for i in range(1, 10):
  for j in range(1, i + 1):
    print("%d * %d = %d" % (j, i, i * j), end='\t')
  print()

输出结果:

1 * 1 = 1
1 * 2 = 2   2 * 2 = 4
1 * 3 = 3   2 * 3 = 6   3 * 3 = 9
1 * 4 = 4   2 * 4 = 8   3 * 4 = 12  4 * 4 = 16
1 * 5 = 5   2 * 5 = 10  3 * 5 = 15  4 * 5 = 20  5 * 5 = 25
1 * 6 = 6   2 * 6 = 12  3 * 6 = 18  4 * 6 = 24  5 * 6 = 30  6 * 6 = 36
1 * 7 = 7   2 * 7 = 14  3 * 7 = 21  4 * 7 = 28  5 * 7 = 35  6 * 7 = 42  7 * 7 = 49
1 * 8 = 8   2 * 8 = 16  3 * 8 = 24  4 * 8 = 32  5 * 8 = 40  6 * 8 = 48  7 * 8 = 56  8 * 8 = 64
1 * 9 = 9   2 * 9 = 18  3 * 9 = 27  4 * 9 = 36  5 * 9 = 45  6 * 9 = 54  7 * 9 = 63  8 * 9 = 72  9 * 9 = 81

以上是关于Python循环的简单介绍,涵盖了for循环、while循环和嵌套循环。在实际开发中,循环结构是必不可少的,希望大家在使用过程中能够熟练掌握。