在Python中使用带有for循环的else条件语句
在大多数编程语言(C/C++、 Java等)中,else 语句的使用受到 if 条件语句的限制。但是Python也允许我们在 for 循环中使用 else 条件。
The else block just after for/while is executed only when the loop is NOT terminated by a break statement.
Else 块在下面的Python 3.x 程序中执行:
Python
for i in range(1, 4):
print(i)
else: # Executed because no break in for
print("No Break")
Python
for i in range(1, 4):
print(i)
break
else: # Not executed as there is a break
print("No Break")
Python
# Python 3.x program to check if an array consists
# of even number
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])
Python
count = 0
while (count < 1):
count = count+1
print(count)
break
else:
print("No Break")
输出 :
1
2
3
No Break
Else 块不会在Python 3.x 或更低版本中执行:
Python
for i in range(1, 4):
print(i)
break
else: # Not executed as there is a break
print("No Break")
输出 :
1
仅当循环内存在 if 条件以某种方式依赖于循环变量时,这种类型的 else 才有用。
在下面的例子中,只有当数组中没有元素是偶数时才会执行else语句,即没有执行任何迭代的if语句。因此,对于数组 [1, 9, 8],if 在循环的第三次迭代中执行,因此在 for 循环之后出现的 else 将被忽略。在数组 [1, 3, 5] 的情况下,任何迭代都不会执行 if ,因此执行循环之后的 else 。
Python
# Python 3.x program to check if an array consists
# of even number
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
作为练习,预测以下程序的输出。
Python
count = 0
while (count < 1):
count = count+1
print(count)
break
else:
print("No Break")