How To Use Else With For Loop Using Python

In this tutorial, learn how to use the else with for loop in Python. As you all know that else statement is the part of if conditional statement in Python. However, in Python, you can also use the else statement with for loop.

The else statement executes after the execution of for loop. However, if you use the break statement inside the for a loop. The else statement will not get executed and it also comes out of the loop.

How to Use Else with For Loop in Python

If you use an else statement after the loop and put a code to execute. You will get the result of the execution of code inside the else and the loop. Use the below method to create your own loop including the else statement.

Output

j
a
r
g
o
n
no break found

The above example contains output with each line contains a single string character. It also contains the output of the code under the else statement.

If Statement in Python For Loop With Else

The conditional statement limits the execution of the loop. There is only a single if conditional statement which reduces the number of iteration. One more thing you should note here that the else statement is not part of the if condition. It also executes only after the completion of execution of certain iterations.

Output

m
y
e
l
f
no break found

The above example prints the string characters excluding the single character “s”. You can change the condition as per your requirement to reduce the number of iterations.

However, you can also reduce all iterations after reaches the true if condition. To perform this task, you have to read further showing the break statement.

Break Statement Inside Iteration with Else Using Python

You can stop performing execution when it reaches the break statement inside the if condition. The else statement after the iteration will also not get executed after it strikes the break inside the if condition.

See the below example to create your own code and use the break with the iteration.

Output

c
h
e
c
k

The above example prints the limited number of string characters. However, you do not use the break statement, the above example gives you more string characters in the result.

You may also like to read

I hope you like this post of how to use else with iteration in Python