Python 循环详解教程 (Python Loop Tutorial)
在 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! ?