Table of Contents
3 scenarios for using the For-Else function
1. Iterate and find elements that are not marked
2. Used to break out of nested loops
3. Assist with handling exceptions
Home Backend Development Python Tutorial For-else: A strange but useful feature in Python

For-else: A strange but useful feature in Python

Apr 13, 2023 pm 08:43 PM
python for-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!
Copy after login

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!
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles