Else Clause on Python While Statement

What is the benefit(s) of having 'else clause' for the while loop in python?

else will not execute if there is a break statement in the loop. From the docs:

The while statement is used for
repeated execution as long as an
expression is true:

while_stmt ::=  "while" expression ":" suite
["else" ":" suite]

This repeatedly tests the expression
and, if it is true, executes the first
suite; if the expression is false
(which may be the first time it is
tested) the suite of the else clause,
if present, is executed and the loop
terminates.

A break statement executed in the
first suite terminates the loop
without executing the else clause’s
suite.
A continue statement executed
in the first suite skips the rest of
the suite and goes back to testing the
expression.

(emphasis mine) This also works for forloops, by the way. It's not often useful, but usually very elegant when it is.


I believe the standard use case is when you are searching through a container to find a value:

for element in container:
if cond(element):
break
else:
# no such element

Notice also that after the loop, element will be defined in the global scope, which is convenient.


I found it counterintuitive until I heard a good explanation from some mailing list:

else suites always execute when a condition has been evaluated to False

So if the condition of a while loop is executed and found false, the loop will stop and the else suite will run. break is different because it exits the loop without testing the condition.

Why does python use 'else' after for and while loops?

It's a strange construct even to seasoned Python coders. When used in conjunction with for-loops it basically means "find some item in the iterable, else if none was found do ...". As in:

found_obj = None
for obj in objects:
if obj.key == search_key:
found_obj = obj
break
else:
print('No object found.')

But anytime you see this construct, a better alternative is to either encapsulate the search in a function:

def find_obj(search_key):
for obj in objects:
if obj.key == search_key:
return obj

Or use a list comprehension:

matching_objs = [o for o in objects if o.key == search_key]
if matching_objs:
print('Found {}'.format(matching_objs[0]))
else:
print('No object found.')

It is not semantically equivalent to the other two versions, but works good enough in non-performance critical code where it doesn't matter whether you iterate the whole list or not. Others may disagree, but I personally would avoid ever using the for-else or while-else blocks in production code.

See also [Python-ideas] Summary of for...else threads

Why is the purpose of the else clause following a for or while loop?

You are wrong about the semantics of for/else. The else clause runs only if the loop completed, for example, if a break statement wasn't encountered.

The typical for/else loop looks like this:

for x in seq:
if cond(x):
break
else:
print "Didn't find an x I liked!"

Think of the "else" as pairing with all of the "if's" in the loop body. Your samples are the same, but with "break" statements in the mix, they are not.

A longer description of the same idea: http://nedbatchelder.com/blog/201110/forelse.html

While loop with if/else statement in Python

counter = 1 
while (counter <= 5):
if counter < 2:
print("Less than 2")
elif counter > 4:
print("Greater than 4")
counter += 1

This will do what you want (if less than 2, print this etc.)

Python else statement inside and outside while loop

while loops can have elses in Python. From while statements:

while_stmt ::=  "while" expression ":" suite
["else" ":" suite]

This [the while statement] repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.

While else statement equivalent for Java?

The closest Java equivalent is to explicitly keep track of whether you exited the loop with a break... but you don't actually have a break in your code, so using a while-else was pointless in the first place.

For Java folks (and Python folks) who don't know what Python's while-else does, an else clause on a while loop executes if the loop ends without a break. Another way to think about it is that it executes if the while condition is false, just like with an if statement.

A while-else that actually had a break:

while whatever():
if whatever_else():
break
do_stuff()
else:
finish_up()

could be translated to

boolean noBreak = true;
while (whatever()) {
if (whateverElse()) {
noBreak = false;
break;
}
doStuff();
}
if (noBreak) {
finishUp();
}

How to execute an if else statement in while loop without making the while loop stop?

Soo, I'm also kinda new to programming and python so I don't exactly how to make a timer with that functionality. What is happening is that when you use the input() function the code stops and waits for the user input.

I know you can use some libraries, like pygame, in order to check for user input inside the loop without stopping it, but without one I'm not sure how to do it.

You can also use the module keyboard, that comes inside python, and I think is great for the problem you shared. Check this post How to detect key presses?



Related Topics



Leave a reply



Submit