Python其他循环
Else with 循环与 while 和 for 循环一起使用。 else 块在循环结束时执行意味着当给定的循环条件为假时,else 块被执行。因此,让我们看一下下面带有 else 的 while 循环和 for 循环的示例。
其他与 While 循环
考虑下面的例子。
Python3
i=0
while i<5:
i+=1
print("i =",i)
else:
print("else block is executed")
Python3
l = [1, 2, 3, 4, 5]
for a in l:
print(a)
else:
print("else block is executed")
Python3
def contains_even_number(l):
n = len(l)
i = 0
while i < n:
if l[i] % 2 == 0:
print("list contains an even number")
break
i += 1
# This else executes only if break is NEVER
# reached and loop terminated after all
# iterations
else:
print("list does not contain an even number")
# Driver code
print ("For List 1:")
contains_even_number([1, 9, 8])
print (" \nFor List 2:")
contains_even_number([1, 3, 5])
Python3
def contains_even_number(l):
for ele in l:
if ele % 2 == 0:
print ("list contains an even number")
break
# This else executes only if break is NEVER
# reached and loop terminated after all
# iterations.
else:
print ("list does not contain an even number")
# Driver code
print ("For List 1:")
contains_even_number([1, 9, 8])
print (" \nFor List 2:")
contains_even_number([1, 3, 5])
输出:
i = 1
i = 2
i = 3
i = 4
i = 5
else block is executed
解释
- 声明 i=0
- 我们知道 while 循环一直处于活动状态,直到给定条件为真。我们检查 i<5 直到 i 的值为 4 才为真。
- i+=1 i 的增量,因为我们不想无限次执行 while 循环。
- 打印 i 的值
- 当 i 的值为 5 时,else 块执行。
否则使用 For 循环
考虑下面的例子。
Python3
l = [1, 2, 3, 4, 5]
for a in l:
print(a)
else:
print("else block is executed")
输出:
1
2
3
4
5
else block is executed
解释
- 声明一个列表 l=[1,2,3,4,5]
- for 循环打印 a.
- 当 for 循环读取列表的最后一个元素时,执行 else 块。
否则与 break 语句
仅当循环未被 break 语句终止时,才执行 for/while 之后的 else 块。
在下面的例子中,只有当数组中没有元素是偶数时才会执行else语句,即没有执行任何迭代的if语句。因此,对于数组 [1, 9, 8],if 在循环的第三次迭代中执行,因此在 for 循环之后出现的 else 将被忽略。在数组 [1, 3, 5] 的情况下,任何迭代都不会执行 if ,因此执行循环后的 else 。
示例 1:使用 while 循环
Python3
def contains_even_number(l):
n = len(l)
i = 0
while i < n:
if l[i] % 2 == 0:
print("list contains an even number")
break
i += 1
# This else executes only if break is NEVER
# reached and loop terminated after all
# iterations
else:
print("list does not contain an even number")
# Driver code
print ("For List 1:")
contains_even_number([1, 9, 8])
print (" \nFor List 2:")
contains_even_number([1, 3, 5])
输出:
For List 1:
list contains an even number
For List 2:
list does not contain an even number
示例 2:使用 for 循环
我们将使用与上面相同的示例,但这次我们将使用 for 循环而不是 while 循环。
Python3
def contains_even_number(l):
for ele in l:
if ele % 2 == 0:
print ("list contains an even number")
break
# This else executes only if break is NEVER
# reached and loop terminated after all
# iterations.
else:
print ("list does not contain an even number")
# Driver code
print ("For List 1:")
contains_even_number([1, 9, 8])
print (" \nFor List 2:")
contains_even_number([1, 3, 5])
输出:
For List 1:
list contains an even number
For List 2:
list does not contain an even number