FOR loops in Python have an 'ELSE' clause.. YES!!!
top of page

FOR loops in Python have an 'ELSE' clause.. YES!!!

Updated: Jun 8

Python has more surprises than you think!

As someone who has been teaching Python for many years, I’ve noticed that even seasoned programmers often overlook certain powerful features of the language. These hidden gems can make your code more elegant and efficient.


Did you know Python’s For/While loops have an 'else' clause?

That’s right! It’s not just the if statement that can have an else. You can use else with loops to execute a block of code when the loop completes without hitting a break. Let’s explore this with a practical example:

ree

Scenario: Searching for a Product in a Catalog

Imagine you’re working on an e-commerce platform, searching for a specific product in a list. If the product is found, you want to display its details; if it’s not found, you want to notify the user that the product is unavailable.


products = ["laptop", "smartphone", "headphones", "tablet"]
search_item = "smartwatch"
for product in products:
    if product == search_item:
        print(f"{search_item} is available!")
        break
else:
    print(f"Sorry, {search_item} is not available in our catalog.")

FREE PYTHON MASTERCLASS - 4 HOURS (WEEKEND)

Why Use the else Clause in Loops?

This feature is not just a curiosity—it has practical applications. The else clause in loops can streamline your code and make it more readable. It’s particularly useful when searching or validating conditions across an iterable. When the loop concludes without finding a match, the else block executes, saving you from additional flag variables or checks after the loop.


Curious to discover more hidden Python features? Comment below and let’s dive into the lesser-known corners of this versatile language!






WHICH LANGUGE IS BEST FOR DATA SCIENCE CAREER?

  • R

  • JAVA

  • PYTHON

  • RUBY


bottom of page