search
HomeBackend DevelopmentPython TutorialFor-else: A strange but useful feature in Python

For-else: A strange but useful feature in Python

Apr 13, 2023 pm 08:43 PM
pythonfor-else

For-else: A strange but useful feature in Python

Introduction

No matter which programming language we use, we all write "if-else" statements, but what about "for-else"?

For many languages, such as C, C and Java, using "else" after a loop is completely wrong. However, Python, as an elegant language, has this "strange but useful" feature. If used correctly, our code will become cleaner.

This article will introduce the "for-else" function in Python and explain how to use it correctly through simple examples.

Basic knowledge about the "For-Else" feature

When you first encounter the "for-else" feature, it will look strange and It is difficult to understand (when you first started using this function, it was easy to mistakenly think that else was indented wrong). But in fact, its usage is surprisingly simple. One sentence will suffice: the "else" blocks in your code are only executed when there are no breaks in the loop.

Sound a bit too simple to be true? Let's take a look at an example:

leaders = ["Elon", "Tim", "Warren"]
for i in leaders:
 if i == "Yang":
 print("Yang is a leader!")
 break
else:
 print("Not found Yang!")
# Not found Yang!

As shown above: As shown above, the leaders list does not contain "Yang", so there is no break in our for loop. So the "else" block executes and prints the information.

What if the leaders list contains "Yang"?

leaders = ["Yang", "Elon", "Tim", "Warren"]
for i in leaders:
 if i == "Yang":
 print("Yang is a leader!")
 break
else:
 print("Not found Yang!")
# Yang is a leader!

As shown above, because the leaders list contains "Yang", the for loop is interrupted and the content in the "else" block is not executed.

In short, the for-else feature itself is not difficult to understand, but using it correctly and skillfully is not. Below we introduce three scenarios where the for-else feature is suitable.

3 scenarios for using the For-Else function

We do not necessarily have to use the for-else feature in Python programs. Honestly, we can do the same thing without it, but using it makes our code more elegant.

1. Iterate and find elements that are not marked

Iterating through a list to find specific elements is the basic scenario for using loops. Usually when we find the target element, it makes no sense to continue iterating and we need to break out of the loop. The question is: how do we know if the element is found?

The traditional solution is to define a "mark" variable and set it to True when we find a specific item.

leaders = ["Yang", "Elon", "Tim", "Warren"]
have_yang = False
for i in leaders:
 if i == "Yang":
 have_yang = True
 # Do something
 break
if have_yang == False: # no yang
 ...# Do others

As shown in the above example, the have_yang variable is a flag. After the for loop completes, if its value is False, we know that "Yang" is not in the list and can do some other operations.

This method is good enough, but if you want to take advantage of Python's "elegant" features, using for-else is another option:

leaders = ["Yang", "Elon", "Tim", "Warren"]
for i in leaders:
 if i == "Yang":
 have_yang = True
 # Do something
 break
else:# no yang
 ...# Do others

This way of writing looks like It looks neater, right?

2. Used to break out of nested loops

For-else can also help when there are nested loops in the code.

for i in range(5):
 for j in range(5):
 if j == 2 and i == 0:
 break
 if not (j == 2 and i == 0):
 continue
break

As shown above, breaking out of nested loops is a little difficult because we have to know whether the inner loop is broken out.

The code above shows a clumsy solution to determine whether the inner loop has been interrupted. It certainly works fine, but we can make it neater by using for-else:

# use the for-else syntax
for i in range(5):
 for j in range(5):
 if j == 2 and i == 0:
 break
 else:# only execute when it's no break in the inner loop
 continue
 break

3. Assist with handling exceptions

nums = [1, 3, 0, 5]
for denominator in nums:
 try:
 20/denominator
 except ZeroDivisionError:
 break
else:# no found ZeroDivisionError
 ...# Do others

As shown above, if in the for loop No ZeroDivisionError occurs and we can perform the corresponding subsequent operations in the "else" block.

Summary

The for-else feature in Python may seem a little strange at first, but its usage is not difficult to understand and can be used in certain scenarios. its usefulness. After all, we only have to remember one rule: the "else" block is only executed when there are no breaks in the loop.

The above is the detailed content of For-else: A strange but useful feature in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
What are some common operations that can be performed on Python arrays?What are some common operations that can be performed on Python arrays?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

In what types of applications are NumPy arrays commonly used?In what types of applications are NumPy arrays commonly used?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

When would you choose to use an array over a list in Python?When would you choose to use an array over a list in Python?Apr 26, 2025 am 12:12 AM

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

Are all list operations supported by arrays, and vice versa? Why or why not?Are all list operations supported by arrays, and vice versa? Why or why not?Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

How do you access elements in a Python list?How do you access elements in a Python list?Apr 26, 2025 am 12:03 AM

ToaccesselementsinaPythonlist,useindexing,negativeindexing,slicing,oriteration.1)Indexingstartsat0.2)Negativeindexingaccessesfromtheend.3)Slicingextractsportions.4)Iterationusesforloopsorenumerate.AlwayschecklistlengthtoavoidIndexError.

How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools