目录
1. for 循环
在 Python 里,for
循环主要用于对序列(像列表、元组、字符串等)或者其他可迭代对象进行遍历。其基本格式如下:
for 变量 in 可迭代对象:
代码块
1.1.遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 输出:apple
# banana
# cherry
1.2.遍历字符串
for char in "hello":
print(char)
# 输出:h
# e
# l
# l
# o
1.3.借助 range () 函数循环特定次数
for i in range(5): # 生成 0 到 4 的整数
print(i)
# 输出:0
# 1
# 2
# 3
# 4
2. while 循环
while
循环会在条件表达式为真时,一直重复执行代码块。其基本格式为:
while 条件:
代码块
2.1.简单的 while 循环
count = 0
while count < 5:
print(count)
count += 1
# 输出:0
# 1
# 2
# 3
# 4
2.2.循环读取用户输入
password = ""
while password != "secret":
password = input("请输入密码:")
print("密码正确!")
3. break 与 continue
break
break
语句的作用是终止当前所在的循环,直接跳出循环体,去执行循环后面的代码。
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
if fruit == "banana":
break # 找到 "banana" 后终止循环
print(fruit)
# 输出:ap
continue
continue
语句用于跳过当前循环的剩余代码,直接进入下一次循环。
for i in range(5):
if i % 2 == 0:
continue # 跳过偶数
print(i)
# 输出:1
# 3
4. 循环与 else
在 Python 中,循环可以和 else
子句搭配使用。当循环正常结束(不是通过 break
终止)时,else
子句的代码就会被执行。
for-else
for i in range(3):
print(i)
else:
print("循环结束")
# 输出:0
# 1
# 2
# 循环结束
对比:使用 break 时 else 不执行
for i in range(3):
if i == 1:
break
print(i)
else: # 不会执行
print("循环结束")
# 输出:0
while-else
count = 0
while count < 3:
print(count)
count += 1
else:
print("循环结束")
# 输出:0
# 1
# 2
# 循环结束
对比:使用 break 时 else 不执行
value = int(input("输入一个数:"))
i = 2
while value > i:
if value % i == 0:
print("不是质数")
break
i += 1
else:
print("是")
5.总结
语句 | 功能 |
---|---|
for | 对可迭代对象进行遍历。 |
while | 当条件为真时持续循环。 |
break | 终止循环,不再执行剩余的循环体以及 else 子句(如果有)。 |
continue | 跳过当前循环的剩余代码,直接开始下一次循环。 |
循环 + else | 循环正常结束(没有被 break 终止)时,执行 else 子句中的代码。 |