Python 如何使用循环else语句
在本文中,我们将向您展示如何在Python中使用循环else语句。
我们许多人对术语 else 感到困惑,因为在if-else条件中使用else是有意义的,但是在循环中使用else?太奇怪了!Python为其循环提供了一个附加功能。
循环中的else与while和for循环一起使用。else块在循环结束时运行,这意味着当指定的循环条件为假时执行。
语法
带有可选else子句的for循环
for variable_name in iterable:
#stmts in the loop
.
.
.
else:
#stmts in else clause
.
.
语法
带有可选else子句的for循环
while condition:
#stmts in the loop
.
.
.
else:
#stmts in else clause
.
.
在Python中使用for循环的else语句
在其他语言中,else功能只能与if-else语句配对使用。但是在Python中,我们也可以在for循环中实现else功能。
else功能仅当循环正常终止时才可使用。如果循环被强制终止,解释器将忽略else语句,因此其执行将被跳过。
注意 :当循环没有被 break 语句终止时,紧接在for/while之后的else块将被执行。
方法 1:正常终止的for-else结构(没有break语句)
示例
以下程序展示了如何在for循环中使用else语句:
for i in ['T','P']:
print(i)
else:
# Loop else statement
# there is no break statement in for loop, hence else part gets executed directly
print("ForLoop-else statement successfully executed")
输出
在执行时,上述程序将生成以下输出 –
T
P
ForLoop-else statement successfully executed
方法2:带有强制终止的for-else结构(带有break语句)
示例
以下程序展示了在使用break语句时else条件如何工作-
for i in ['T','P']:
print(i)
break
else:
# Loop else statement
# terminated after 1st iteration due to break statement in for loop
print("Loop-else statement successfully executed")
输出
执行上述程序后将生成以下输出 –
T
解释
如果循环内部有一个依赖于循环变量的if条件,那么else语句类型只在这种情况下有用。
在 方法1 中,循环else语句会被执行,因为for循环在遍历列表[‘T’,’P’]后正常终止。然而,在 方法2 中,循环else语句不会被执行,因为循环使用诸如break之类的跳转语句被强制停止。
这些 方法 清楚地表明当循环被强制终止时,循环else表达式不会被执行。
现在考虑一个示例,其中循环else语句在某些条件下执行,而在其他条件下不执行。
方法3:带有break语句和if条件的for-else结构
示例
以下程序展示了在使用break语句和条件语句的情况下else条件的工作方式-
# creating a function to check whether the list item is a positive
# or a negative number
def positive_or_negative():
# traversing in a list
for i in [5,6,7]:
# checking whether the list element is greater than 0
if i>=0:
# printing positive number if it is greater than or equal to 0
print ("Positive number")
else:
# Else printing Negative number and breaking the loop
print ("Negative number")
break
# Else statement of the for loop
else:
# Statement inside the else block
print ("Loop-else Executed")
# Calling the above-created function
positive_or_negative()
输出
执行上述程序后将生成以下输出−
Positive number
Positive number
Positive number
Loop-else Executed
使用Python中的while循环的else语句
没有break语句的Else-While
步骤
以下是执行所需任务的算法/步骤:
- 将k的值初始化为0。
-
使用while循环遍历,直到指定条件为真(直到k<8)。
-
将k的值增加1,因为我们不希望无限次执行while循环。
-
打印k的值。
-
当条件失败/变为假时,即当k的值变为8时,执行else块。
示例
以下程序演示了在while循环中使用else语句的用法:
k=0
# traversing until the condition is true(k<8)
while k<8:
# incrementing the k value by 1
k+=1
# printing k value
print("k =",k)
else:
# else block gets executed when the condition fails(becomes false)
print("This is an else block")
输出
执行上述程序后,将会生成如下输出:
k = 1
k = 2
k = 3
k = 4
k = 5
k = 6
k = 7
k = 8
This is an else block
在While循环中使用Else语句和break语句
示例
以下程序展示了在while循环中使用break语句时else条件的工作方式:
# creating a function that checks if the
# list passed to it contains an even number
def hasEvenNumber(l):
# getting the list length
n = len(l)
# intializing a variable with 0(index)
i = 0
# traversing the loop until the I value is less than the list length
while i < n:
# checking whether the corresponding index element of a list is even
if l[i] % 2 == 0:
# printing some text, if the condition is true
print("The input list contains an even number")
# giving a break statement/break the loop
break
# incrementing the I (index) value by 1
i += 1
else:
# Else print "The input list doesn't contain an even number"
# It executes Only if the break is NEVER met and the loop is terminated after all iterations
print("The input list doesn't contain an even number")
# calling the hasEvenNumber() function by passing input list 1 as an argument
print("For Input list 1:")
hasEvenNumber([3, 9, 4, 5])
# calling the hasEvenNumber() function by passing input list 2 as an argument
print("For Input list 2:")
hasEvenNumber([7, 3, 5, 1])
输出
执行上述程序后,将生成以下输出结果 –
For Input list 1:
The input list contains an even number
For Input list 2:
The input list doesn't contain an even number
结论
这篇文章教了我们如何在Python的for和while循环中使用else语句。此外,我们还学习了在else语句中使用break语句时的行为。