Member-only story
3 Chaotic Python Features To Avoid
Steer clear of these confusing snippets
In the last couple of decades, Python has become one of the most popular programming languages for general purposes. Thus, it has been adopted by people in different domains, such as finance, science, and engineering. One of the reasons for Python’s popularity is its versatility — there are often different approaches to achieve the same functionalities. However, some approaches can be confusing to others. In those cases, you should consider alternatives.
In this article, I’ll discuss a few Python features that can be confusing — particularly to beginners. As a comparison, I’ll provide alternatives that implement the same functionalities. As you’ll see, alternatives may require more code, but they should be preferred because of their clarity. After all, readability is the biggest goal that you should strive to achieve for your coding project.
The else Clause in for/while Loops
Most programming languages share similar features regarding the for
and while
loops. They have the following general form:
for item in list_or_array:
do something with the itemwhile some_condition_evaluated:
do something
They are intuitive to all of us, regardless of our programming levels. However, Python allows the else
clause to be used with for
and while
loops. Observe these features below:
We see the else
clause most frequently in an if…else…
statement in which the else
clause runs only when the previous if
clause doesn’t run. This behavior may make some people think the same thing happens to the else
clauses in for
and while
loops. However, if you run the above code, you’ll find out that both else
clauses run in each case.
Thus, the rule for the else
clause in these cases is that it will be skipped only when there is a break
statement executed in the for
or while
clause. Observe the contrast below: