Python tips for reducing loop layers and indentation, python indentation

Source: Internet
Author: User

Python tips for reducing loop layers and indentation, python indentation

This article provides an example of how to reduce the circular hierarchy and indentation of Python. 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.

Related Article

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.