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!

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
