How to use Python to reduce loop layers and indentation skills

Source: Internet
Author: User
This article mainly introduces Python's techniques for reducing loop layers and indentation, and analyzes in detail the Python code jumping out of the loop in combination with the instance form, which has some reference value, if you need it, you can refer to the example in this article to analyze Python's skills for reducing loop layers and indentation. We will share this with you for your reference. The details are as follows:

We know that the colon and indentation in Python represent braces, which can save a lot of code lines, but can be more optimized to reduce the levels and indentation of loops as much as possible to make the code look more concise, the logic is clearer. This is not only true for Python, but also for other languages.

The two sections are Python code. the functions to be implemented in the first and second sections are the same, but the second section is obviously more readable and the logic is clearer. When many loops are nested, we can actually use "reverse thinking" to jump out of a non-conforming loop with "continue" instead of continuing to execute it when it is set up. this will only deepen the hierarchy of loops.

The following is the Python code in the figure:

"For item in items: if is_for_sale (item): cost = compute_cost (item) if cost <= wallet. money: buy (item) "after Optimization" for item in items: if not is_for_sale (item): continue cost = compute_cost (item) if cost> wallet. money: continue buy (item)

This reduces the hierarchy of nested loops, making readability and logic more intuitive and less indented.

For more articles on how to use Python to reduce the cycle levels and indentation skills, refer to PHP!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.