Is it possible to add an else statement with a loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Is it possible to add an else statement with a loop

is it possible

3rd Aug 2017, 10:47 AM
Efe Onobrakpeya
Efe Onobrakpeya - avatar
3 Answers
+ 2
yes it is possible. for "while" and "for" loops, the else condition is executed in case that the loop was left under normal conditions, this means no "break" occured within the loop Further, even a "try" statement can have an "else". In this case the else condition is executed when no error occured within the try-block
3rd Aug 2017, 11:43 AM
Martin Ed
Martin Ed - avatar
+ 5
I believe this is a case of trying to verify something using a for loop, and, if all the iterations are false, then print something. You can do it using booleans, e.g arr = [5, 3, 9, 7, 2] isAllOdd = True for i in arr: if i%2 == 0: isAllOdd = False if isAllOdd: print('All members are odd.') else: print('arr contains even values.')
3rd Aug 2017, 11:26 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
for i in range 10 if i%2 == 0: print(i) else: print("ODD") #we have a for loop #containing an if / else statement #this code print every even number #and replace odd number by "ODD"
3rd Aug 2017, 11:17 AM
coutable.n
coutable.n - avatar