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!