Loop is a commonly used program control structure. We often say that one of the greatest advantages of machines over humans is that machines can do something repeatedly without sleep, but humans cannot.“Circulation” is the key concept that allows machines to repeat their work continuously.In terms of loop syntax, Python is both traditional and unconventional. Although it abandoned the common for (init; condition; incrment) three-stage structure, it still chose the two classic keywords for and while to express the loop. In most cases, our cycle requirements can be satisfied with for <item> in <iterable>, while while <condition> is used less.Although the syntax of the loop is simple, it is not easy to write it. In this article, we will explore what is “authentic” loop code, and how to write them.

What is the “authentic” cycle?

The word “authentic” is often used to describe someone doing something, very consistent with local traditions, and doing very well.Since the word “authentic” often describes real things like accents and cooking tastes, what does the “authentic” loop code mean? Let me explain with a classic example.If you ask someone who has just learned Python for a month: “ How to get the current index while traversing a list?”. He may hand over this code:

Although the above loop is correct, it is not “authentic” at all. A person with three years of Python development experience will say that the code should be written like this:

enumerate() is a built-in Python function that takes an “iterable” object as a parameter, and then returns a new iterable object that keeps generating as (current subscript, current element)This is the best way to use it in this scenario.

In the above example, we would think that the second loop code is more “authentic” than the first. Because it uses more intuitive code, the work is done smarter.

#programming #towards-data-science #data-science #python #technology

Tips for Writing Authentic Loops In Python
1.45 GEEK