The for/else Statement in Python

TheAutomatic.net

Contributor:
TheAutomatic.net
Visit: TheAutomatic.net

By:

Blogger, TheAutomatic.net, and Senior Data Scientist

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 for/else statement

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...

while/else statements

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

Conclusion

That’s it for now! If you liked this post, please share with your friends, or subscribe to get notified about future posts!

Visit TheAutomatic.net for additional insight on this topic.

Disclosure: Interactive Brokers

Information posted on IBKR Traders’ Insight that is provided by third-parties and not by Interactive Brokers does NOT constitute a recommendation by Interactive Brokers that you should contract for the services of that third party. Third-party participants who contribute to IBKR Traders’ Insight are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from TheAutomatic.net and is being posted with permission from TheAutomatic.net. The views expressed in this material are solely those of the author and/or TheAutomatic.net and IBKR is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

In accordance with EU regulation: The statements in this document shall not be considered as an objective or independent explanation of the matters. Please note that this document (a) has not been prepared in accordance with legal requirements designed to promote the independence of investment research, and (b) is not subject to any prohibition on dealing ahead of the dissemination or publication of investment research.

Any trading symbols displayed are for illustrative purposes only and are not intended to portray recommendations.