Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the else clause in Python

Shulou Source: shulou.com Published: 2022-06-01 04:16:11 10月17日 Update

This article will explain in detail how to use the else clause in Python. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Else clause

The else clause in Python can be used not only in if statements, but also in for, while, and try statements.

The else block is run only when the for loop or the while loop finishes running normally (rather than through a break statement or a return statement or an exception exits the loop).

For example:

For i in range (3):... Print (I)... Else:... Print ('Iterated over everything'). 012Iterated over everything >

As above, the for loop ends normally, so the subsequent else block is run.

For i in range (3):... If I = = 2RV... Break... Print (I)... Else:... Print ('Iterated over everything'). 01 >

From this, you can see that the for loop will not run the subsequent else block if it does not run properly (such as the one above is the end of the break loop).

The try block is run only if no exception is thrown in the else block. At first, you may not feel the need to use the else clause in the try/except block. After all, in the following code snippet, after_call () executes only if dangerous_call () does not throw an exception, right?

Try: dangerous_call () after_call () except OSError: log ('OSError...')

However, after_call () should not be placed in the try block. For clarity, only statements that throw expected exceptions should be included in the try block. Therefore, it is better to write as follows:

Try: dangerous_call () except OSError: log ('OSError...') else: after_call ()

It is now clear that the try block defends against possible errors in dangerous_call (), not after_call (). And obviously, after_call () is executed only if the try block does not throw an exception. Note, however, that the exception thrown by the else clause is not handled by the previous except clause, which means that if after_call () throws an exception at this point, it will not be caught.

This is the end of the article on "how to use the else clause in Python". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Clauses loops runs statements articles only more good practical obvious necessary that is code examples content such as above articles fragments thus Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Huawei OPPO Reno Redmi Shulou Tech Info