【Python中`for`循环和`while`循环详细介绍及其用法。】

循环结构是编程中用来重复执行一段代码的重要工具。在Python中,主要的循环结构有for循环和while循环。以下是对这两种循环结构的详细介绍及其用法。

1. for 循环

for 循环用于遍历一个序列(如列表、元组、字符串)或其他可迭代对象。

基本语法
python 复制代码
for item in iterable:
    # 执行代码块
示例
python 复制代码
# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
python 复制代码
# 遍历字符串
for letter in "Python":
    print(letter)
python 复制代码
# 使用range()函数遍历一系列数字
for i in range(5):  # range(5)生成0到4的数字
    print(i)

2. while 循环

while 循环在给定条件为真时反复执行代码块。

基本语法
python 复制代码
while condition:
    # 执行代码块
示例
python 复制代码
count = 0
while count < 5:
    print(count)
    count += 1

3. 循环控制语句

break 语句

break 语句用于提前终止循环。

python 复制代码
for i in range(10):
    if i == 5:
        break
    print(i)
continue 语句

continue 语句用于跳过本次循环剩余的代码,直接进入下一次循环。

python 复制代码
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)

4. 嵌套循环

循环可以嵌套,即在一个循环内部再使用另一个循环。

示例
python 复制代码
for i in range(3):
    for j in range(3):
        print(f"i = {i}, j = {j}")

5. else 子句

循环还可以带有else子句,当循环正常结束时(即没有遇到break),会执行else子句中的代码。

示例
python 复制代码
for i in range(5):
    print(i)
else:
    print("循环结束")
python 复制代码
for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print("循环结束")

实践案例:求一个列表中的所有数字之和

使用 for 循环
python 复制代码
numbers = [1, 2, 3, 4, 5]
total = 0

for number in numbers:
    total += number

print(f"总和是: {total}")
使用 while 循环
python 复制代码
numbers = [1, 2, 3, 4, 5]
total = 0
index = 0

while index < len(numbers):
    total += numbers[index]
    index += 1

print(f"总和是: {total}")

实践案例:寻找质数

一个数如果只能被1和它本身整除,那么它就是质数。下面的代码使用循环结构来找出一定范围内的质数。

python 复制代码
start = 10
end = 50

print(f"{start}到{end}之间的质数有:")

for num in range(start, end + 1):
    if num > 1:
        for i in range(2, num):
            if num % i == 0:
                break
        else:
            print(num)

总结

循环结构是编程中的基础工具,掌握for循环和while循环及其控制语句breakcontinue的用法,可以帮助你高效地处理重复性任务。通过不断练习和应用这些概念,你会逐渐熟悉和灵活运用循环结构来解决各种编程问题。

相关推荐
FishCoderh27 分钟前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅30 分钟前
Python函数入门详解(定义+调用+参数)
python
曲幽2 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时5 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿7 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee1 天前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay1 天前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python