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.