Python For-Else and While-Else Clearly Explained with Real-World Examples - Python Simplified (2023)

  • February 12, 2021
  • Author -Swathi Ambi
  • Category -Python

Python For-Else and While-Else Clearly Explained with Real-World Examples - Python Simplified (1)

Table of Contents

Introduction

Did you know that in Python for and while loops have an else clause? Why do we have it? What does it mean? How does it work? Where can you use it in your day to day work? Come, let us explore!

Understand For-Else and While-Else

For many of us, the term else creates confusion, because else in an if-else statement makes sense but an else for a loop? Weird! For a moment, stop trying to make sense of the word else. Just think that Python is offering you an additional feature with its loops. Let us see how it works.

Syntax

The for loop with optional else clause:

for variable_name in iterable: #stmts in the loop . . .else: #stmts in else clause . . .

The while loop with optional else clause:

while condition: #stmts in the loop . . .else: #stmts in else clause . . .
(Video) #20 Python Tutorial for Beginners | While Loop in Python
  • The else clause will not be executed if the loop gets terminated by a break statement.
  • If a loop does not hit a break statement, then the else clause will be executed once after the loop has completed all its iterations (meaning, after the loop has completed normally).

Python For-Else and While-Else Clearly Explained with Real-World Examples - Python Simplified (2)

Python For-Else and While-Else Clearly Explained with Real-World Examples - Python Simplified (3)

Python For-Else and While-Else Clearly Explained with Real-World Examples - Python Simplified (4)

Raymond Hettinger, a Python pioneer mentioned in one of his presentations to always comment #no break next to the else clause of a loop in Python. If loop’s else was termed as nobreak instead, then there would have been no confusion.

Simplified Real-World Examples

Are you thinking, what’s the point? How can this be of any use to me? Come, let’s explore some interesting applications which can be useful for you.

A) Search

Traditional Approach

Traditionally, flags were used in search programs to keep a tab on whether a value was found or not. If you had to search for more values, then it increased the complexity of maintaining many flag variables.

Traditionally, flags were used in search programs to keep a tab on whether a value was found or not. If you had to search for more values, then it increased the complexity of maintaining many flag variables.

#************************ Traditionally ************************# set flag = 0# loop the items in the data# if the item was found in the loop then set flag = 1# display search result by verifying the flag value#***************************************************************

Better Approach in Python

But with Python, you could easily write a search program without having to use any flags. You could instead use a break statement and the loop’s else clause, to get the job done easily. A simple search example is given below.

my_treasure_box = ["a", "b", "Diamond", "c"]def search(search_item): for item in my_treasure_box: if(item==search_item): print(f"{search_item} Found!") break else: print(f"No {search_item} found.") search("Diamond")search("Gold")#-------Output--------#Diamond Found!#No Gold found.

B) To CheckLimits

(Video) What a performance 🔥👏 #shorts

Traditional Approach

Traditionally, a flag variable was used to check if the data has breached given limits.

#*************************Traditionally*************************# set flag = 1# loop the items in the data# if any item breaches the given limits then set flag = 0# display the validation result by verifying the flag value#***************************************************************

Better Approach in Python

But with Python, you could easily validate this using a break statement and loop’s else clause. No flags are needed. Take a look at the example below.

lower_limit = 5upper_limit = 10def validate_limits(input_data): for i in input_data: if(i <= lower_limit or i >= upper_limit): print(f"{input_data}: At least one value breaches limits.") break else: #no break print(f"{input_data}: Successful Validation!")validate_limits([1, 6, 11])validate_limits([6, 7, 8])#------------Output------------#[1, 6, 11]: At least one value breaches limits.#[6, 7, 8]: Successful Validation!

C) NestedLoops

Traditional Approach

Older languages had GOTO statements to alter the line of execution in a program. This approach was tricky and hence had more chance of committing a human error. If you had nested loops and a couple of GOTO statements in them, then it only added more complexity and risk.

#************************Older Languages************************# outer_label: outer loop# inner loop# if a condition was met, GOTO outer_label#***************************************************************

Better Approach in Python

But in Python, there is no GOTO statement and that’s a good thing. In fact, this is one of the reasons why Python introduced break and loop’s else statements  ( to replace the GOTO statement). Hence, making it easier and safer for programmers to use them.

  • When we have to manage nested loops, we can easily break from an inner loop and get the line of execution to the outer loop using a break statement.
  • And if you need to check whether the inner loop completed executing all its iterations normally without hitting a break statement, you could use the loop’s else clause.

Note: Keep in mind that in Python, you cannot break multiple nested loops using a single break statement. One break statement can only break the one loop which contains it.

To understand this clearly, take a look at the example below.

teams_data = [ {"team_name": "A", "team_scores": [5, 3, 2]}, {"team_name": "B", "team_scores": [4, 2, None]} ]for team in teams_data: total_score = 0 name = team["team_name"] for score in team["team_scores"]: if score == None: print(f"Team {name} Score: Incomplete Data") break total_score += score else: print(f"Team {name} Score: {total_score}")#------------Output------------#Team A Score: 10#Team B Score: Incomplete Data

D) Use with Exception Handling

If you want to terminate a loop if it raises an exception, then you could use a break statement in the except block. Further, if you want to execute some statements only if the loop has completed normally (meaning, completed all its iterations without hitting a break) then you could write those statements inside the loop’s else clause. Go through the below example to understand it better.

def multiply(my_data): result = 1 for i in my_data: try: result *= i except TypeError: print(f"{my_data}: Invalid Data") break else: print(f"{my_data} Multiplication Result: {result}") multiply([2, 3, 6])multiply(['a', 'b'])#------------Output------------#[2, 3, 6] Multiplication Result: 36#['a', 'b']: Invalid Data
(Video) Transforming Code into Beautiful, Idiomatic Python

Takeaway:

1. The else clause of a loop (for/while) gets executed only if the loop has completed its execution fully without hitting a break statement (in other words, loop has completed normally).

2. The statements inside the loop’s else clause will get executed once after the loop has completed normally.

3. How to keep confusion away? Think of the loop’s else clause as no-break. Always comment #no break next to the loop’s else clause, a best practice for better code readability suggested by Raymond Hettinger, a Python pioneer.

4. Where can you use it?

  • To search (instead of using flags, use break and loop’s else).
  • To check limits/boundaries (instead of using flags, use break and loop’s else).
  • To manage nested loops (when you need to take action based on whether the inner loop got executed normally or hit a break statement).
  • You could use it along with exception handling (when you need to break on exception and execute certain statements only if the loop was completed normally).

5. A Word of Caution: Always verify the indentation of the loop’s else clause, to check if it is properly aligned (indented) with the loop keyword(for/while). By mistake, if a loop’s else clause gets aligned (indented) with an if statement, then the code will break.

With this, I hope that you are confident about for-else and while-else in Python. You also got familiar with a few of its applications. Repeat with me “No More Confusion:)”!

Please comment below if you have come across any other applications (uses) of for-else and while-else.

References

Python For-Else and While-Else Clearly Explained with Real-World Examples - Python Simplified (5)

Swathi Ambi

A Technical Blogger passionate about cutting edge technologies, currently writing on Python and Angular. Previously worked as a Software Engineer & Team Lead with over 10+ years of experience in the IT industry, India and USA.

Python For-Else and While-Else Clearly Explained with Real-World Examples - Python Simplified (6)

Swathi Ambi

A Technical Blogger passionate about cutting edge technologies, currently writing on Python and Angular. Previously worked as a Software Engineer & Team Lead with over 10+ years of experience in the IT industry, India and USA.

3 thoughts on “Python For-Else and While-Else Clearly Explained with Real-World Examples”

  1. Python For-Else and While-Else Clearly Explained with Real-World Examples - Python Simplified (7)

    Sai

    March 5, 2021 at 2:22 am

    Great article & very good examples of the use cases. You’ve touched upon a recurring pain point in loops and given an elegant solution.

    Reply

    1. Python For-Else and While-Else Clearly Explained with Real-World Examples - Python Simplified (8)

      Swathi Ambi

      March 5, 2021 at 5:34 pm

      Thank you Sai :), glad to know that it helped!

  2. Python For-Else and While-Else Clearly Explained with Real-World Examples - Python Simplified (9)

    salman

    January 25, 2022 at 8:05 am

    hello and gratitude for what you did here swathi 🙂

    “””
    Traditionally, flags were used in search programs to keep a tab on whether a value was found or not. If you had to search for more values, then it increased the complexity of maintaining many flag variables.
    “””

    you’ve typed this phrase twice

    Reply

Leave a Comment

(Video) Python for Beginners - Learn Python in 1 Hour

PrevPreviousHow to Use MongoDB to Store and Retrieve MLModels

(Video) World's Most Realistic Drawing #shorts

NextPython Parameters And Arguments DemystifiedNext

Videos

1. Elon Musk: SpaceX, Mars, Tesla Autopilot, Self-Driving, Robotics, and AI | Lex Fridman Podcast #252
(Lex Fridman)
2. Daylight Saving Time Explained
(CGP Grey)
3. Javascript Promises vs Async Await EXPLAINED (in 5 minutes)
(Roberts Dev Talk)
4. [CLASSIFIED] "Only a Few People On Earth Know About It"
(Be Inspired)
5. Don't use ChatGPT until you've watched this video!
(Alden Adison)
6. What If We Swallowed A Hair? | Hairs In Our Stomach | The Dr Binocs Show | Peekaboo Kidz
(Peekaboo Kidz)
Top Articles
Latest Posts
Article information

Author: Cheryll Lueilwitz

Last Updated: 19/04/2023

Views: 5553

Rating: 4.3 / 5 (54 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Cheryll Lueilwitz

Birthday: 1997-12-23

Address: 4653 O'Kon Hill, Lake Juanstad, AR 65469

Phone: +494124489301

Job: Marketing Representative

Hobby: Reading, Ice skating, Foraging, BASE jumping, Hiking, Skateboarding, Kayaking

Introduction: My name is Cheryll Lueilwitz, I am a sparkling, clean, super, lucky, joyous, outstanding, lucky person who loves writing and wants to share my knowledge and understanding with you.