One of the first things you usually learn when starting a new language is the if-else construct of that language. Python, like some other languages, offers an extended variation of this called the “for/else” statement. Let’s check out a couple examples to see how it works!
The main use case for the for/else statement is when you need to loop through a list with the potential to break out of the loop. If a break occurs in the loop, the code within the else clause will not be executed. However, if a break does not occur, then the code within the else clause will be executed.
For example, in the code below we initialize test = False. Then we loop through each element in the list, nums. If an element in nums equals 20, we break out of the loop. Since no element equals 20, we never break out of the loop, and therefore, the else clause is executed, which changes the value of test to equal True.
nums = [10, 4, 6, 8, 2] test = False for num in nums: if num == 20: break else: test = True
In general, rather than just flagging a variable as True / False, you might want to perform some additional actions based off whether the break occurred.
nums = [10, 4, 6, 8, 2] test = False for num in nums: if num == 20: # do something here if 20 is found... break else: test = True # do additional code here in case 20 is never found...
In addition to for/else statements, Python also supports while/else statements. We can modify our code above to use a while/else statement like this:
nums = [10, 4, 6, 8, 2] test = False i = 0 while i in range(len(nums)): if nums[i] == 20: break i += 1 else: test = True
That’s it for now! If you liked this post, please share with your friends, or subscribe to get notified about future posts!
Very excited to announce the early-access preview (MEAP) of my upcoming book, Software Engineering for…
Ever had long-running code that you don't know when it's going to finish running? If…
Background If you've done any type of data analysis in Python, chances are you've probably…
In this post, we will investigate the pandas_profiling and sweetviz packages, which can be used…
In this post, we're going to cover how to plot XGBoost trees in R. XGBoost…
In this post, we'll discuss the underrated Python collections package, which is part of the…