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!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



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.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

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.

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.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.
