Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the `else:` correct/necessary in this Python program?

Is the line of else: correct/necessary in this Python program?

from random import randrange
for n in range(10):
    r = randrange(0,10) # get random int in [0,10)
    if n==r: continue # skip iteration if n=r
    if n>r: break # exit the loop if n>r
    print n
else:
    print "wow, you are lucky!\n"
if n<9:
    print "better luck next time\n
like image 795
qazwsx Avatar asked Jun 19 '26 11:06

qazwsx


1 Answers

From the documentation:

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement

So yes, it's correct in your example. Although I've never been a fan of it, using an else clause on a loop makes code confusing at first, I'd rather use a boolean flag for achieving the same effect. IMHO else should be used only for conditionals.

like image 91
Óscar López Avatar answered Jun 21 '26 00:06

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!