What is a for else in Python With Example?

In Python, a for-else loop is a unique type of loop that combines the for loop with an else block.

The general syntax of a for-else loop in Python is as follows:

for item in iterable:
    # Loop body
    # Code to process each item in the iterable
    if some_condition:
        break
else:
    # Code in the else block
    # This code will be executed if the loop completes all iterations without encountering a 'break' statement
Code language: Python (python)

Here’s how the for-else loop works:

  1. The loop iterates over each item in the iterable.
  2. If the loop encounters a break statement during its execution (usually due to a certain condition being met), the loop is terminated immediately, and the code in the else block is not executed.
  3. If the loop completes all iterations without encountering a break statement, the code in the else block is executed.

The for-else loop can be helpful when you want to perform some additional actions or handle specific cases after iterating over all elements in a collection without a premature termination.

Let’s see an example:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num == 3:
        print("Found the number 3!")
        break
else:
    print("Number 3 not found in the list.")
Code language: Python (python)

Output:

Found the number 3!Code language: Python (python)

In this example, the loop finds the number 3 in the list, and the break statement is executed, causing the else block not to be executed. If the number 3 was not present in the list, the else block would have been executed, indicating that the number 3 was not found.

Can you use 2 else in Python?


No, in Python, you cannot have two else blocks for a single if statement or a single loop. The else block is associated with the nearest preceding if statement or loop, and there can be only one else block per if statement or loop construct.

For if statements, the syntax is as follows:

if condition:
    # Code block executed if the condition is true
else:
    # Code block executed if the condition is false
Code language: Python (python)

For loops, the else block is used in conjunction with the for or while loop, and it is executed only if the loop completes all iterations without encountering a break statement.

Here’s the syntax for for-else loop:

for item in iterable:
    # Loop body
else:
    # Code block executed if the loop completes all iterations without a 'break' statement
Code language: Python (python)

And for while-else loop:

while condition:
    # Loop body
else:
    # Code block executed if the condition becomes False (loop terminates) without a 'break' statement
Code language: Python (python)

Remember, you can have nested if statements or nested loops, and each of them can have its own else block, but at any given level of nesting, there should be only one else block.

What is Elif in Python?


In Python, elif is a keyword that stands for “else if.” It is used as a part of the if statement to chain multiple conditions together and provide an alternative set of instructions when the previous condition(s) in the if statement are not met.

The syntax for using elif in Python is as follows:

if condition1:
    # Code block executed if condition1 is true
elif condition2:
    # Code block executed if condition1 is false and condition2 is true
elif condition3:
    # Code block executed if both condition1 and condition2 are false, and condition3 is true
else:
    # Code block executed if none of the above conditions are true
Code language: Python (python)

Here’s how it works:

  1. The if statement is evaluated first. If the condition following if is true, the corresponding code block is executed, and the rest of the elif and else blocks are skipped.
  2. If the condition following if is false, the first elif condition is checked. If it is true, the corresponding code block is executed, and the rest of the elif and else blocks are skipped.
  3. The process continues sequentially through each elif condition until a true condition is found, and its corresponding code block is executed.
  4. If none of the conditions (including the if and all elif conditions) are true, the else block is executed.

The elif keyword allows you to handle multiple cases and provides a more comprehensive decision-making structure in your code.

The elif keyword becomes especially valuable when you need to evaluate multiple distinct conditions and execute specific blocks of code depending on which condition is satisfied first. It provides a concise and organized way to handle various mutually exclusive scenarios in your code.

Read More;

  • I am an enthusiastic learner and aspiring Python developer with expertise in Django and Flask. I pursued my education at Ivan Franko Lviv University, specializing in the Faculty of Physics. My skills encompass Python programming, backend development, and working with databases. I am well-versed in various computer software, including Ubuntu, Linux, MaximDL, LabView, C/C++, and Python, among others.

    View all posts

Leave a Comment