Python for 和 while 循环:掌握循环控制的基本操作
本文详细介绍了 Python 中的
for
和
while
循环的使用方法,帮助你轻松掌握循环控制的基本操作。通过
for
循环,你可以在有限范围内迭代执行代码块,而
while
循环则适用于条件控制的场景,甚至可以实现无限循环。此外,文章还讲解了
continue
和
break
关键字的作用,分别用于跳过当前循环或终止循环。通过丰富的代码示例,本文展示了如何在不同情况下使用这些循环结构,使你的代码更加灵活和高效。文章最后附有完整的代码示例,便于读者实际操作和理解。
一 for 循环
# for 循环 python
for i in range(5):
print("新文件-" + str(i))
print()
for i in range(2, 5):
print("新文件-" + str(i))
print()
for i in range(3, 10, 2):
print("新文件-" + str(i))
二 while 循环
guess_num = 10
while guess_num != 20:
guess_num += 1
print(guess_num)
三 两个循还的特点
关键字 | 特点 |
---|---|
for | 天然适合在有限的循环中 |
while | 可以被用在无限循环中 |
四 continue 和 break
# continue 和 break
count = 0
guess_num = 30
while guess_num != 20 and count <= 10:
guess_num -= 1
count += 1
print(guess_num)
print()
count = 0
guess_num = 10
while guess_num != 20:
guess_num += 1
count += 1
if count > 10:
break
print(guess_num)
print()
for i in range(10):
if i == 5:
break
print(i)
print()
for i in range(10):
if i % 2 == 0:
continue # 跳过偶数
print(i)
注解
关键字 | 描述 |
---|---|
break | 中止循环 |
continue | 跳出当前循环,进行下一个循环 |
五 完整文件示例
# This is a sample Python script.
# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press ⌘F8 to toggle the breakpoint.
# for 循环
for i in range(5):
print("新文件-" + str(i))
print()
for i in range(2, 5):
print("新文件-" + str(i))
print()
for i in range(3, 10, 2):
print("新文件-" + str(i))
print()
# While 循环
# for 天然适合在有限的循环中
# while 可以被用在无限循环中
guess_num = 10
while guess_num != 20:
guess_num += 1
print(guess_num)
print()
# continue 和 break
count = 0
guess_num = 30
while guess_num != 20 and count <= 10:
guess_num -= 1
count += 1
print(guess_num)
print()
count = 0
guess_num = 10
while guess_num != 20:
guess_num += 1
count += 1
if count > 10:
break
print(guess_num)
print()
for i in range(10):
if i == 5:
break
print(i)
print()
for i in range(10):
if i % 2 == 0:
continue # 跳过偶数
print(i)
# break 中止循环
# continue 跳出当前循环,进行下一个循环
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('for 和 while 循环')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
复制粘贴并覆盖到你的 main.py 中运行,运行结果如下。
Hi, for 和 while 循环
新文件-0
新文件-1
新文件-2
新文件-3
新文件-4
新文件-2
新文件-3
新文件-4
新文件-3
新文件-5
新文件-7
新文件-9
11
12
13
14
15
16
17
18
19
20
29
28
27
26
25
24
23
22
21
20
11
12
13
14
15
16
17
18
19
20
0
1
2
3
4
1
3
5
7
9
六 源码地址
代码地址:
国内看 Gitee 之 for 和 while 循环.py
国外看 GitHub 之 for 和 while 循环.py
详情见:莫烦 Python