Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (20.3k points)

I've noticed the following code is legal in Python. My question is why? Is there a specific reason?

n = 5

while n != 0:

    print n

    n -= 1

else:

    print "what the..."

2 Answers

0 votes
by (20.3k points)

The else clause only gets executed when your while condition becomes false. So, if you are breaking out of the loop, or if an exception is raised, then it won't be executed. You can try using if/else construct with respect to the condition like this:

if condition:

    handle_true()

else:

    handle_false()

is analogous to the looping construct:

while condition:

    handle_true()

else:

    # condition is false now, handle and go on with the rest of the program

    handle_false()

An example will be along the lines of:

while value < threshold:

    if not process_acceptable_value(value):

        # something went wrong, exit the loop; don't pass go, don't collect 200

        break

    value = update(value)

else:

    # value >= threshold; pass go, collect 200

    handle_threshold_reached()

0 votes
by (20.3k points)

The else clause only gets executed when your while condition becomes false. So, if you are breaking out of the loop, or if an exception is raised, then it won't be executed. You can try using if/else construct with respect to the condition like this:

if condition:

    handle_true()

else:

    handle_false()

is analogous to the looping construct:

while condition:

    handle_true()

else:

    # condition is false now, handle and go on with the rest of the program

    handle_false()

The example will be along the lines of:

while value < threshold:

    if not process_acceptable_value(value):

        # something went wrong, exit the loop; don't pass go, don't collect 200

        break

    value = update(value)

else:

    # value >= threshold; pass go, collect 200

    handle_threshold_reached()

Related questions

0 votes
1 answer
0 votes
4 answers
0 votes
1 answer
+2 votes
1 answer

Browse Categories

...