值得收藏!16段代码入门Python循环语句("新手必备!16段实用代码轻松掌握Python循环语句")
原创
一、Python循环语句简介
Python中的循环语句核心包括两种:for循环和while循环。这两种循环在处理重复任务时非常有用。下面将通过16段代码来入门Python循环语句。
二、for循环
for循环通常用于遍历序列(如列表、元组、字符串)中的元素。
1. 遍历列表
for item in [1, 2, 3, 4, 5]:
print(item)
2. 遍历字符串
for char in "Hello, World!":
print(char)
3. 遍历元组
for element in (1, 2, 3, 4, 5):
print(element)
4. 使用range()函数
for i in range(5):
print(i)
5. 使用range()函数指定开端和终止值
for i in range(1, 6):
print(i)
6. 使用range()函数指定步长
for i in range(0, 10, 2):
print(i)
7. 使用enumerate()函数遍历列表并获取索引
for index, value in enumerate(["apple", "banana", "cherry"]):
print(index, value)
三、while循环
while循环用于在满足条件的情况下重复执行代码块。
8. 基本while循环
count = 0
while count < 5:
print(count)
count += 1
9. 使用break语句退出循环
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
10. 使用continue语句跳过当前迭代
for i in range(5):
if i == 2:
continue
print(i)
11. 使用else语句在循环终止后执行代码
count = 0
while count < 5:
print(count)
count += 1
else:
print("循环终止")
四、循环控制语句
12. 使用break语句退出多层循环
for i in range(5):
for j in range(5):
if i == 2 and j == 2:
break
print(i, j)
13. 使用pass语句作为占位符
for i in range(5):
if i == 2:
pass
else:
print(i)
五、循环嵌套
14. 使用嵌套for循环打印乘法表
for i in range(1, 10):
for j in range(1, i+1):
print(f"{j}x{i}={i*j}", end="\t")
print()
15. 使用嵌套while循环打印乘法表
i = 1
while i < 10:
j = 1
while j <= i:
print(f"{j}x{i}={i*j}", end="\t")
j += 1
print()
i += 1
16. 使用列表推导式简化循环
multiplication_table = [[f"{j}x{i}={i*j}" for j in range(1, i+1)] for i in range(1, 10)]
for row in multiplication_table:
print("\t".join(row))
六、总结
通过以上16段代码,相信你已经对Python循环语句有了基本的了解。循环语句在编程中非常重要,掌握它们可以帮助你更高效地解决问题。在实际编程中,请凭借需求灵活运用循环语句。