for-else
structure?The for-else
structure is a unique combination that allows you to run a loop (the for
part) and then execute a block of code (the else
part) if the loop completes normally, without being interrupted by a break
statement.
for
part: This is just like any other for
loop, where you iterate over a sequence (like a list, tuple, or string) or any other iterable object.else
part: This block of code executes only if the for
loop completed all its iterations without encountering a break
statement. If a break
is hit, the else
block is skipped.Let's say you have a list of names, and you're looking for a specific name. If you find the name, you want to print a message. If you don't find the name after checking the whole list, you want to print a different message.
names = ["Alice", "Bob", "Charlie", "Diana"] search_name = "Charlie" for name in names: if name == search_name: print(f"{search_name} found!") break else: # This part runs if the name was not found print(f"{search_name} not found in the list.")
In this example, if search_name
is in the names
list, it prints that the name was found and exits the loop with break
, skipping the else
block. If the loop completes without finding the name, it then runs the else
block.
Let's use the for-else
structure to check if a number is prime. A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.
def is_prime(number): if number <= 1: return False for i in range(2, int(number**0.5) + 1): if number % i == 0: print(f"{number} is not a prime number.") break else: # This part runs if the number has no divisors other than 1 and itself print(f"{number} is a prime number.") is_prime(11) # This should print that 11 is a prime number. is_prime(10) # This should print that 10 is not a prime number.
In this prime number checker, the for
loop checks for divisors of the given number
. If it finds a divisor, it prints that the number is not prime and breaks out of the loop. If the loop completes without finding any divisors (other than 1 and the number itself), the else
block runs, indicating the number is prime.
for-else
structure?It is particularly useful in search operations and conditions where completing a loop without interruptions is a significant condition.
The for-else
structure can make your code cleaner and more readable by eliminating the need for additional flags or checks outside the loop to determine if the loop completed normally.