else in the end of for and while loops | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

else in the end of for and while loops

who can say me: What is the difference between writing code inside else or just after the loops? for x in range(6): print('hello') print('bye') or for x in range(6): print('hello') else: print('bye')

9th Apr 2022, 10:39 AM
TheFutureProgrammer
TheFutureProgrammer - avatar
3 Answers
+ 2
The `else` block after a while...loop or a for...loop is executed ONLY when the loop completed the entire loop iterations without any `break` statement issued. If the loop broke out somewhere, then the `else` block will not be executed. In first example, "bye" will be printed unconditionally, whether the loop completed with or without `break` statement issued, "bye" will be printed. In second example, "bye" will be printed ONLY when the loop completed without any `break` statement issued ever.
9th Apr 2022, 1:22 PM
Ipang
- 2
I think that the `else` keyword is there because in some cases there is needed an action to be done right after the loop ends. So I guess that the loop should end right after the `else` part is executed. On the other hand, this really can't make a big difference in most of cases as it can just be another part or whatever that doesn't require to be connected with a loop. Anyways, is a good opportunity to check Python Docs and Features.
9th Apr 2022, 11:21 AM
Ervis Meta
Ervis Meta - avatar
- 3
The will cause an error. You NEED a previous if statement if you want an else statement. You can also just run the code and see for yourself
9th Apr 2022, 10:43 AM
Slick
Slick - avatar