Home > database >  else in the end of for and while loops
else in the end of for and while loops

Time:04-05

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')

CodePudding user response:

From for/else documentation:

The else clause executes after the loop completes normally. This means that the loop did not encounter a break statement.

This means that in your specific example there is no difference in using else or not.

CodePudding user response:

In the second example you're using conditional statement, Whereas in the first scenario after the loop completes, It automatically executes the next line.

Basically your post is an example of getting same result with alternative solutions.

Though your first solution can be considered as valid practice comparing with second one.

Although I would suggest you to read this article before posting any questions on stack overflow.

  • Related