Other syntax elements you may not know yet
There are some elements of the Python syntax that are not popular and rarely used. It is because they either provide very little gain or their usage is simply hard to memorize. Due to this, many Python programmers (even with years of experience) simply do not know about their existence. The most notable examples of such features are as follows:
- The
for … else
clause - Function annotations
The for … else … statement
Using the else
clause after the for
loop allows you to execute a code of block only if the loop ended "naturally" without terminating with the break
statement:
>>> for number in range(1): ... break ... else: ... print("no break") ... >>> >>> for number in range(1): ... pass ... else: ... print("break") ... break
This comes in handy in some situations because it helps to remove some "sentinel" variables that may be required if the user wants...