Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python String
Next article icon
Using else conditional statement with for loop in python

In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops.
 

The else block just after for/while is executed only when the loop is NOT terminated by a break statement.


Else block is executed in below Python 3.x program: 

Python
foriinrange(1,4):print(i)else:# Executed because no break in forprint("No Break")

Output : 

123No Break


Else block is NOT executed in Python 3.x or below: 

Python
foriinrange(1,4):print(i)breakelse:# Not executed as there is a breakprint("No Break")

Output : 

1


Such type of else is useful only if there is an if condition present inside the loop which somehow depends on the loop variable.
In the following example, the else statement will only be executed if no element of the array is even, i.e. if statement has not been executed for any iteration. Therefore for the array [1, 9, 8] the if is executed in the third iteration of the loop and hence the else present after the for loop is ignored. In the case of array [1, 3, 5] the if is not executed for any iteration and hence the else after the loop is executed.

Python
# Python 3.x program to check if an array consists# of even numberdefcontains_even_number(l):foreleinl:ifele%2==0:print("list contains an even number")break# This else executes only if break is NEVER# reached and loop terminated after all iterations.else:print("list does not contain an even number")# Driver codeprint("For List 1:")contains_even_number([1,9,8])print("\nFor List 2:")contains_even_number([1,3,5])

Output: 

For List 1:list contains an even numberFor List 2:list does not contain an even number


As anexercise, predict the output of the following program. 

Python
count=0while(count<1):count=count+1print(count)breakelse:print("No Break")

For Else in Python
Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp