Python For Else

Welcome to the fascinating world of Python programming! Today, let’s explore the ‘for-else’ loop, a cool feature that can make your code more powerful. Read this article to learn more about Python For Else.

However, Python’s ‘for‘ loop is excellent for that. Now, the ‘else‘ part adds a twist – it gets executed if your loop completes without any interruptions.

What is Else in For Loop?

The else keyword in the loop will denote the block of code that will run only when the loop is completed.

Example 1 for Else Keyword in Python

# Example: Checking if a number is prime

num = 11  # You can change this number to test different cases

for i in range(2, num):
    if num % i == 0:
        print(f"{num} is not a prime number.")
    print(f"{num} is a prime number.")


11 is a prime number.

Important note: The else block cannot run the program, when the loop is either stopped by the break statement.

Example 2

# Example: Using break to exit a loop

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for num in numbers:
    if num == 6:
        print(f"Loop is broken because num is {num}")
    print(f"Processing {num}")

print("Loop finished.")


Processing 1
Processing 2
Processing 3
Processing 4
Processing 5
Loop is broken because num is 6


To conclude, this article has listed Python for else keywords. Several examples are illustrated for a better understanding of the concept. Hence, Students can improve their skills and knowledge of Python for else keywords.

Python For Else- FAQs

Q1.What is the use case for else in Python?

Ans. Python consists of a command known as elif. This means that it will go after an if.

Q2. What is else in coding?

Ans. The ELSE Statement has an alternate processing that will occur when the condition of matching IF statements is not satisfied.

Q3. What are if and else statements?

Ans. If/else statement will run the code only when the condition comes true.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment