Python 循环详解教程 (Python Loop Tutorial)

liftword4个月前 (02-20)技术文章69

在 Python 中,循环结构帮助我们自动重复执行代码(automatically execute the code repetitively),大大提高了编程效率!

本教程将通过详细示例(Through detailed exemplifications),带你深入理解 for 循环、while 循环、嵌套循环、循环控制语句和列表推导式。Let's dive in!


1. for 循环 (for Loop) ??

for 循环主要用于遍历各种序列(如列表、元组、字符串等)。每次迭代时,将序列中当前的元素赋值给变量,然后执行循环体代码。
(For loops iterate over a sequence, assigning each element to a variable and executing the code block.)

语法结构:

for 变量 in 序列:    # for variable in sequence:
    # 循环体代码   # code block

示例 1:遍历列表

food = ['黄瓜', '绿叶', '蛋糕']
for my_food in food:
    print("我喜欢:" + my_food)  

示例 2:遍历字符串

word = "Python"
for char in word:
    print(char)

2. while 循环 (while Loop)

while 循环会在给定条件为 True 时不断执行循环体,直到条件变为 False。
(While loops continue executing as long as the condition is True.)

语法结构:

while 条件:    # while condition:
    # 循环体代码   # code block

示例 1:基本计数循环 ??

count = 1
while count <= 5:
    print("计数:" + str(count))
    count += 1  # 等同于 count = count + 1

示例 2:输入验证实例

password = ""
while password != "secret":
    password = input("请输入密码:")  # Please input password:
print("密码正确,欢迎进入系统!")  # Correct password, welcome!

3. 嵌套循环 (Nested Loops)

当需要在一个循环内部再使用另一个循环时,就称为嵌套循环。常用于处理二维数据或多重结构。
(Nested loops are used when you need a loop inside another loop, such as for processing matrices.)

示例:二维矩阵遍历

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:
    for num in row:
        print(str(num) + " ", end="")  # 每个数字后加空格
    print()  # 换行

示例:打印九九乘法表 ??

for i in range(1, 10):
    for j in range(1, i+1):
        print(f"{j}x{i}={i*j}", end="\t")  # 使用制表符间隔
    print()  # 换行

输出结果示例:

1x1=1	
1x2=2	2x2=4	
1x3=3	2x3=6	3x3=9	

4. 循环控制语句 (Loop Control Statements) ??

在循环中,我们可以使用以下语句来改变循环的执行流程:

  • break:立即退出整个循环。
    (Break: exits the loop immediately.)
    示例:
for i in range(10): 
	if i == 3: 
  	break # 当 i 等于 3 时退出循环 
	print("数字:" + str(i))  #数字:0 数字:1 数字:2
  • continue:跳过当前循环剩余部分,直接开始下一次迭代。
    (Continue: skips the rest of the current iteration.)
    示例:
for i in range(1, 6): 
	if i % 2 == 0: 
  	continue # 跳过偶数 
	print("奇数:" + str(i)) #奇数:1 奇数:3 奇数:5
  • else:当循环没有因 break 而中断时,会执行 else 代码块。
    (Else: executes when the loop finishes normally without break.)
    示例:
for num in range(3): 
	print("迭代:" + str(num)) 
else: 
	print("循环正常结束!")
#输出:
迭代:0
迭代:1
迭代:2
循环正常结束!

5. 列表推导式 (List Comprehension)

列表推导式是一种简洁优雅的写法,用于从一个可迭代对象生成新列表,同时可以嵌入条件判断
(List comprehensions provide a concise syntax for generating lists from iterables, optionally with conditions.)

基本语法:

新列表 = [表达式 for 变量 in 可迭代对象 if 条件]

示例 1:生成平方数列表

squares = [x**2 for x in range(1, 11)]  # 1到10的平方
print("平方数列表:" + str(squares))

输出:

平方数列表:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

示例 2:筛选奇数列表

odds = [x for x in range(1, 21) if x % 2 != 0]
print("奇数列表:" + str(odds))

输出:

奇数列表:[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

6. 高级循环技巧与实战案例 (Advanced Techniques & Practical Examples)

示例:计算列表元素之和

使用 for 循环:

numbers = [5, 10, 15, 20]
total = 0
for num in numbers:
    total += num
print("列表总和:" + str(total))

使用列表推导式和内置函数:

total = sum([num for num in numbers])
print("列表总和(内置函数):" + str(total))

示例:反转字符串

text = "Hello, Python!"
reversed_text = ""
for char in text:
    reversed_text = char + reversed_text  # 将当前字符放在前面
print("反转后的字符串:" + reversed_text)

示例:打印斐波那契数列

n_terms = 10
a, b = 0, 1
print("斐波那契数列:", end="")
for _ in range(n_terms):
    print(a, end=" ")
    a, b = b, a + b  # 同时更新 a 和 b
print()

输出示例:

斐波那契数列:0 1 1 2 3 5 8 13 21 34 

7. 小贴士与注意事项 (Tips & Caveats)

  • 避免无限循环:确保 while 循环中条件会在循环体内改变,否则容易导致无限循环
    (Avoid infinite loops by updating the condition inside the loop.)

  • 正确缩进:Python 对缩进极其敏感,确保每个循环块都保持一致的缩进格式。
    (Proper indentation is crucial in Python.)

  • 使用内置函数:Python 提供了许多内置函数(如 range、sum、enumerate 等),能使循环更加简洁高效。
    (Use built-in functions to simplify your code.)

  • 适当使用列表推导式:虽然推导式代码简洁,但对于逻辑复杂的情况,建议使用传统循环以保持可读性。
    (For complex logic, traditional loops might be clearer than list comprehensions.)

总结

通过丰富的示例代码和图标展示,希望能帮助你更好地理解循环的强大功能,为编写高效代码打下坚实基础!
(Understanding loops will empower you to write concise and efficient code.)

如果你觉得这篇教程对你有帮助,请点赞、收藏并关注我! Happy coding! ?

相关文章

python中的for循环详细介绍_python之for循环详解

在python中,for循环可以遍历任何序列,比如列表、字符串。for循环的基本格式如下:for 变量 in序列: 循环语句1、遍历字符串通过for循环遍历字符串“Hello python”str_w...

6个实例,8段代码,详解Python中的for循环

作者:奥斯瓦尔德·坎佩萨托(Oswald Campesato)来源:华章科技Python 支持for循环,它的语法与其他语言(如JavaScript 或Java)稍有不同。下面的代码块演示如何在Pyt...

Python第十一课:循环语句的详细介绍

本章节将为大家介绍 Python 循环语句的使用。Python 中的循环语句有 for 和 while。Python 循环语句的控制结构图如下所示:while 循环Python 中 while 语句的...

Python | for 循环_python for循环的用法

前言在代码中有的时候我们需要程序不断地重复执行某一种操作例如我们需要不停的判断某一列表中存放的数据是否大于 0,这个时候就需要使用循环控制语句这里会讲解 for 循环python 有两种循环语句,一个...

一文掌握Python 中的迭代器_python3迭代器

1. 迭代器简介在 Python 编程领域,迭代器在简化数据处理和提高代码效率方面发挥着关键作用。在 Python 中,迭代器是一个对象,它允许程序员遍历集合的所有元素,而不管其特定结构如何。了解迭代...

Python for循环几种常用场景_python for循环详解

#程序员##python##python自学##计算机#一、概述可迭代的对象可以使用for循环进行遍历,例如:字符串、列表、字典、元组和集合for循环里面有一个隐藏的机制,就是自动执行inde...