Python Chinese Community The spiritual tribe of Python Chinese developers around the world.jpg”)

Else, we’re pretty familiar with that. For a Python programmer, else is always used in conjunction with if, like this:

Copy the code
  1. a = '12'
  2. if a == '123':
  3.    print(a)
  4. else:
  5. Print (' Error! ')

However, else in Python is not only used after if, so this time we’ll talk about else in Python flow control.

The else clause can be used not only in if statements, but also in for, while, and try statements, a feature of the language that is not a secret but has not received much attention. Let’s look at an example:

Copy the code
  1. my_list = ['apple', 'pear', 'orange', 'banana']
  2. ` `
  3. for item in my_list:
  4.    if item == 'banana':
  5. print('Founded! ')
  6.        break
  7. else:
  8. raise ValueError('No banana flavor found! ')

In this case, the loop finds ‘banana’ and outputs ‘Founded! ‘, and breaks out of the loop, so the else clause is not executed. If, however, the code is modified to remove the ‘banana’ from the list:

Copy the code
  1. my_list = ['apple', 'pear', 'orange']
  2. ` `
  3. for item in my_list:
  4.    if item == 'banana':
  5. print('Founded! ')
  6.        break
  7. else:
  8. raise ValueError('No banana flavor found! ')

Running the code throws an error! If we do not use the else clause, we might need to set the control flag, like this:

Copy the code
  1. my_list = ['apple', 'pear', 'orange']
  2. flag = True
  3. for item in my_list:
  4.    if item == 'banana':
  5. print('Founded! ')
  6.        flag = False
  7.        break
  8. if flag:
  9. raise ValueError('No banana flavor found! ')

Obviously, the additional variables flag and if statements are used.

While is similar to for, here’s a quick example:

Copy the code
  1. a = 'apple'
  2. while a == 'banana':
  3.    pass
  4. else:
  5. raise ValueError('No banana flavor found! ')

Let’s look at try:

Copy the code
  1. try:
  2.    dangerous_call()
  3. except OSError:
  4. log('OSError... ')
  5. else:
  6.    after_call()

It is clear that the try block protects against dangerouscall() errors, and it is clear that aftercall() is executed only if the try block does not throw an exception.

Now, summarize the behavior of the else clause as follows:

for:

The else block is run only when the for loop completes (that is, the for loop is not terminated by a break statement).

while:

The else block is run only if the while loop exits because the condition is false (that is, the while loop is not terminated by a break statement).

try:

The else block is run only if no exception is thrown in the try block.

That is, if an exception or a return, break, or continue statement causes control to jump outside the main block of the compound statement, the else clause is also skipped.

For /else, while/else, and try/else are semantically related, but very different from if/else. It’s mainly the meaning of the word else that gets in the way of understanding these features. The normal understanding is “run this cycle or do that”. In loops, however, the else semantics are just the opposite: “Run this loop and then do that.” However, I believe that use a few times, you will be familiar with.

Recent Hot articles

Learn more about wechat friends \ with Python

How to be a dirty programmer in Python \

New discovery of using Python to crawl 100,000 comments on Eason Chan’s new song “We” \

Using Python to analyze Apple stock price data \

Python Natural Language Processing analysis of heaven and dragon

Click **** to read the original article and become a free member of **** community