Python 循环之零基础入门第十七课

Python 有两个原始的循环命令:

  • while 循环
  • for 循环

while 循环

—— 如果使用 while 循环,只要条件为真,我们就可以执行一组语句。

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

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

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

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

else 语句
通过使用 else 语句,当条件不再成立时,我们可以运行一次代码块:
例子

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")

for 循环

  • for 循环用于迭代序列(即列表,元组,字典,集合或字符串)。
  • 这与其他编程语言中的 for 关键字不太相似,而是更像其他面向对象编程语言中的迭代器方法。
  • 通过使用 for 循环,我们可以为列表、元组、集合中的每个项目等执行一组语句。

例子

a = ["apple", "banana", "cherry"]
for x in a:
  print(x)

遍历出a列表中的所有项

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

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

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

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

else关键字
for 循环中的 else 关键字指定循环结束时要执行的代码块:

for x in range(10):
  print(x)
else:
  print("打印结束")

pass 语句
for 语句不能为空,但是如果您处于某种原因写了无内容的 for 语句,请使用 pass 语句来避免错误。
例子

for x in range(1,10):
  pass

你可能感兴趣的:(python零基础教程)