In Python, we might find else clause in if statement, for, while loops, and try block also. else clause is optional in all these statements. Let’s see how else block is executed in all these statements and loops.
在Python中,我们可能会在if语句, for , while循环中找到else子句 ,并且还会try块。 在所有这些语句中, else子句都是可选的。 让我们看看在所有这些语句和循环中else块是如何执行的。
Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way.
复合语句包含(其他组)其他语句; 它们以某种方式影响或控制其他语句的执行。
if,while,for, try are compound statements.
if , while , for , try是复合语句。
The if, while and for statements implement traditional control flow constructs.
if , while和for语句实现传统的控制流构造。
try specifies exception handlers and/or cleanup code for a group of statements.
try为一组语句指定异常处理程序和/或清除代码。
A compound statement consists of one or more ‘clauses.’
复合语句由一个或多个“ 子句 ”组成。
A clause consists of a header and a ‘suite.’
子句由标题和“ 套件”组成 。
The clause headers of a particular compound statement are all at the same indentation level. 特定复合语句的子句标题都处于相同的缩进级别。Each clause header begins with a uniquely identifying keyword and ends with a colon.
每个子句头均以唯一标识的关键字开头,以冒号结尾。
A suite is a group of statements controlled by a clause.
套件是由子句控制的一组语句。
The if statement is used for conditional execution.
if语句用于条件执行。
If statement will select exactly one of the suites by evaluating the expressions one by one until one is found to be true, then that suite is executed (and no other part of the if statement is executed or evaluated).
如果if语句通过逐个求值直到发现一个表达式为真,将选择一个套件中的一个,则该套件将被执行(并且if语句的其他部分均不会执行或评估)。
If all expressions are false, the suite of the else clause, if present, is executed.
如果所有表达式均为假,则执行else子句套件(如果存在)。
Only one suite will be executed in the if statement.[either if-suite or elif-suite or else-suite).
if语句中将只执行一个套件。[if-suite或elif-suite或else-suite)。
There can be zero or more elif clause, and the else clause is optional.
可以有零个或多个elif子句, else子句是可选的。
Photo by Author 作者照片Example 1: If-else clause
示例1:If-else子句
Executed the below code three times.
执行了以下代码三遍。
First-time input is given as 7. If clause x>5 evaluated to True and only if suite is executed. No other part of the if statement is evaluated or executed.
首次输入为7 。 如果子句x>5评估为True,且仅在执行套件时才被评估。 if语句的其他部分均不会评估或执行。
Second-time input is given as 5. If clause x>5 and elif clause x<5 is evaluated to False, so by default else suite is executed.
第二次输入的给定为5.如果子句x>5和elif子句x<5的求值为False,则默认情况下将执行suite 。
Third-time input is given as 3.If clause x>5 is evaluated to False. Then elif clause evaluated returns True, so elif suite is executed. Else clause is not executed.
第三次输入为3如果子句x>5的计算结果为False。 然后评估的elif子句返回True,因此执行了elif suite 。 其他子句不执行。
x = int(input("Please enter an integer: "))if x>5: print ("Greater than 5")elif x<5: print ("Less than 5")else: print ("The number is 5")print ("Outside if-else block")''' Output 1 : Please enter an integer: 7 Greater than 5Outside if-else blockOutput 2:Please enter an integer: 5The number is 5Outside if-else blockOutput 3:Please enter an integer: 3Less than 5Outside if-else block'''The for statement is used to iterate over the elements of a sequence (such as a string, tuple, or list) or other iterable objects.
for语句用于遍历序列的元素(例如字符串,元组或列表)或其他可迭代对象。
for loop may have an else clause; it is executed when the for loop terminates through exhaustion of the iterable.But not when the loop is terminated by a break statement.
for循环可能包含else子句; 它在for循环通过迭代器的穷举而终止时执行,但在以break语句终止时则不执行。
Syntax:
句法:
for item in iterable: suiteelse:suite The iterable is evaluated only once. An iterator is created for the result of that iterable. 可迭代仅被评估一次。 为该可迭代的结果创建一个迭代器。The suite is then executed once for each item provided by the iterator, in the order returned by the iterator.
然后按迭代器返回的顺序,对迭代器提供的每个项目执行一次套件 。
When the items are exhausted, the suite in the else clause, if present, is executed, and the loop terminates.
当项目用尽时,将执行else子句中的套件(如果存在),并终止循环。
Image by Author 图片作者else clause is executed when the for loop terminates after the exhaustion of the iterable.
当for循环在迭代器用尽后终止时,将执行else子句 。
for i in [1,2,3,4,5]: print (i)else: print ("for loop is done")print ("Outside the for loop")'''12345for loop is doneOutside the for loop'''The while statement is used for repeated execution as long as an expression is true.
只要表达式为真, while语句将用于重复执行。
while expression: suiteelse: suite Photo by Author 作者照片This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.
这将反复测试表达式,如果为true,则执行第一个套件;否则,将执行第一个套件。 如果表达式为假(可能是第一次测试),则执行else子句套件(如果存在)的套件,并终止循环。
Example 9: Using else clause in a while loop.
示例9:在while循环中使用else子句。
while loop is executed until the condition i<5 is False.
执行while循环 ,直到条件i<5为False。
else clause is executed after the condition is False.
条件为False后执行else子句 。
i=0while i<5: print (i) i+=1else: print ("Element is greater than 5")'''Output:01234Element is greater than 5'''Refer to my story break,continue statements in for,while loop
请参阅我的故事休息,在for,while循环中继续声明
The try statement specifies exception handlers and/or cleanup code for a group of statements:
try语句为一组语句指定异常处理程序和/或清除代码:
Syntax:
句法:
try: suiteexcept Exception: suiteelse: suitefinally: suitetry:In the try block, code is executed and if an exception is raised, control goes to the except clause. If no exception is raised, no exception handler is executed.
try:在try块中,执行代码,如果引发异常,则控制权转到except子句。 如果没有引发异常,则不会执行任何异常处理程序。
except:The except clause(s) specify one or more exception handlers.This block is executed only if an exception is raised in the try block.
除了: except子句指定一个或多个异常处理程序。仅在try块中引发异常时才执行此块。
else:else clause is executed if the control flow leaves the try suite, no exception was raised, and no return, continue, or break statement was executed.
else:如果控制流离开了try套件,没有引发异常,并且没有执行return,continue或break语句,则执行else子句。
finally:finally specifies a ‘cleanup’ handler.This block is always executed even if there is an exception raised in the try block or not.
最终: finally指定一个``清理''处理程序。即使try块中是否引发异常,该块始终执行。
Even when a return, break or continue statement is executed in the try suite of a try…finally statement, the finally clause is also executed ‘on the way out.’
即使在try … finally语句的try套件中执行了return,break或 finally语句时, finally子句也将在“出路”上执行。
Image by Author 图片作者Example 1: Exception is not raised in the try block.
示例1:try块中未引发异常。
try, except, and finally block are executed.
尝试,除了,最后执行块。
def add(a,b):try: result=a+bexcept Exception as e: print (e)else: print (result)finally: print ("Executed finally")add(4,5)'''Output:9Executed finally'''Example 2: Exception is raised by try block.
示例2:try块引发异常。
try, except and finally blocks are executed
尝试,除了,最后执行块
def add(a,b):try: result=a+bexcept Exception as e: print (e)else: print (result)finally: print ("Executed finally")add({'a':1},{'b':2})'''Output:unsupported operand type(s) for +: 'dict' and 'dict'Executed finally'''else clause is optional in if, for, while, and try block.
else子句在if , for , while和try块中是可选的。
Only one suite will be executed in the if statement.[either if-suite or elif-suite or else-suite).
if语句中将只执行一个套件。[if-suite或elif-suite或else-suite)。
else clause is executed if there is no exception raised in the try block 如果try块中没有引发异常,则执行else子句else clause in for loop is executed when the for loop terminates through exhaustion of the iterable and not being terminated by a break statement.
当for循环通过穷尽可迭代而终止并且未由break语句终止时,将执行for循环中的else子句。
In the while loop, the else clause is executed after the condition is False. if break statement is executed in the while suite, it will terminate the loop without executing the else clause’s suite.
在while循环中,条件为False后执行else子句 。 如果break语句在while套件中执行,它将终止循环而不执行else子句的套件。
I hope you have found this article helpful — thanks for reading!
希望本文对您有所帮助-感谢您的阅读!
while-else clause
while-else子句
for-else clause
for-else子句
try-else clause
try-else子句
if-else clause
if-else子句
Exceptions
例外情况
Compound statements
复合陈述
翻译自: https://levelup.gitconnected.com/4-else-clauses-in-python-d4e7ccd2432
相关资源:python的else子句使用指南