python如何循环执行

原创
ithorizon 7个月前 (09-29) 阅读数 37 #Python

Python中的循环执行

Python提供了两种主要的循环结构:whilefor

1、while循环

while循环会一直执行代码块,直到给定的条件不再满足。

count = 0
while count < 5:
    print("Count is: ", count)
    count += 1

2、for循环

for循环用于遍历集合(如列表、元组、字典等)中的元素。

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print("I like: ", fruit)

除了基本的循环结构,Python还提供了breakcontinue语句,用于在循环中提前结束或跳过当前的迭代。

3、break语句

break语句用于立即结束当前的循环。

for num in range(10):
    if num == 5:
        break
    print(num)

4、continue语句

continue语句用于跳过当前的迭代,并开始下一次的迭代。

for num in range(10):
    if num == 5:
        continue
    print(num)

Python还提供了else子句,用于在循环完全执行后执行一些操作。

5、else子句

else子句在循环完全执行后执行,无论循环是因为条件不再满足而结束,还是因为break语句而结束。

for num in range(10):
    if num == 5:
        break
    print(num)
else:
    print("Loop finished")


热门