Last Updated on May 15, 2024 by Roshan Parihar
Else with for loop in Python is part of if conditional statement in Python However, you can use else statement inside the for loop without using if condition.
Let’s find out the use with the examples given below.
How to Use Else with For Loop in Python
You can use an else statement inside the loop and put a code to execute. It gives the result of the execution of code inside the else and the loop. Use the below method to create your loop including the else statement.
Examples 1
1 2 3 4 5 |
myStr = "jargon" for i in myStr: print(i) else: print("no break found") |
Output
a
r
g
o
n
no break found
The above example contains output with each line containing a single string character. It also contains the output of the code under the else statement.
If Statement in For Loop With Else in Python
The conditional statement limits the execution of the loop. There is only a single if conditional statement which reduces the number of iterations.
One more thing you should note here is that the else statement is not part of the if condition. It also executes only after the completion of execution of certain iterations.
Examples 2
1 2 3 4 5 6 |
myStr = "myself" for i in myStr: if i != "s": print(i) else: print("no break found") |
Output
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 reaching the true if condition. To perform this task, you have to read further showing the break statement.
Break Statement Inside Iteration in 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 code and use the break with the iteration.
Examples 3
1 2 3 4 5 6 7 |
myStr = "checkmate" for i in myStr: if i == "m": break print(i) else: print("no break found") |
Output
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