Interesting stuff in Python (part 1)

Jyothi
2 min readMay 10, 2024

for … else construct

In Python, an else block code segment can be added for the for loop. The purpose of this else block is to execute after the completion of the for loop. However, the else block will not execute if the for loop contains a break statement and that break statement is executed during the for loop. Therefore, this else block is useful when a break statement is used in the for loop and some code needs to be executed only when that break statement is not executed.

While … else

Similar to the “for…else” construct, the “else” statement can also be used with a “while” loop. There are cases where we need to iterate through a loop and break out of it when a certain condition is met. In languages like C, we have to check if the loop came out due to the break condition. However, with this “else” construct, it can be written directly.

f — strings

F-strings are a type of string formatting in Python, similar to C language’s sprintf or printf. They allow for the insertion of variable values or expressions into string literals, making it easier to format print statements and frame strings that include variable values. F-strings have a wide range of uses beyond formatting print statements and are a powerful tool for working with strings in Python.

--

--