How else part work in continue statement? - python

I'm not sure how the continue statement is interpreted when it is inside a for loop with an else clause.
If the condition is true, the break will exit from a for loop and else part will not be executed. And if the condition is False then else part will be executed.
But, what about continue statement? I tested it seems that the after the continue statement is reached, the else part will be executed. Is this true?? Here is a code example:
# when condition found and it's `true` then `else` part is executing :
edibles = ["ham", "spam", "eggs","nuts"]
for food in edibles:
if food == "spam":
print("No more spam please!")
continue
print("Great, delicious " + food)
else:
print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")`
If I remove "spam" from the list, now the condition is always false and never found but still the else part is executed:
edibles = ["ham","eggs","nuts"]
for food in edibles:
if food == "spam":
print("No more spam please!")
continue
print("Great, delicious " + food)
else:
print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")

With a for loop in Python, the else block is executed when the loop finishes normally, i.e. there is no break statement. A continue does not affect it either way.
If the for loop ends because of a break statement, then else block will not execute. If the loop exits normally (no break), then the else block will be executed.
From the docs:
When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs.
I always remember it because of how Raymond Hettinger describes it. He said it should have been called nobreak instead of else. (That's also a good video that explains the usefulness of the for-else construct)
Example:
numbers = [1,2,3]
for number in numbers:
if number == 4:
print("4 was found")
break
else:
print("4 was not found")
When you run the above code, since 4 is not in the list, the loop will not break and the else clause will print. If you add 4 to the list and run it again, it will break and the else will not print. In most other languages, you would have to add some sentinel boolean like found and make it True if you find a 4, then only print the statement after the loop if found is False.

Your else part will be executed in both cases.
else part executed when loop terminate when condition didn't found.Which is what is happening in your code. But it will also work same without continue statement.
now what about break statement's else part, Break statement's else part will be executed only if:
If the loop completes normally without any break.
If the loop doesn't encounter a break.

Related

Does continue prevent the else block from running in a for/else statement?

In a for loop with break statements I can add an else statement at the end, which will be triggered if my for loop never hits a break statement.
My question is, how does continue affect this?
continue does not affect the else: clause. The else clause is run if the loop terminated normally, that is, if a StopIteration is (implicitly) raised by the iterator.
The continue statement does nothing for the particular iteration, however it does not prevent the iterator from being exhausted.
No, else clause execution is not affected by continue.
The only thing that prevents an else statement (after a for loop) from being triggered is a break statement (or your code returning or exiting or raising an exception before it finishes the for loop).
for i in range(5):
continue
else:
print("else triggered")
Will print else triggered.
See the docs:
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
[...]
When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs.
Only break is mentioned as preventing the else clause from running, continue isn't.

if, elif and else.. priority and chains

I always had this curiosity about Python and I can't find a clear answer, maybe someone can help me
what is the "if", "elif" and "else" priority and way of working?
if I do:
if conditionA:
do something
elif conditionB:
do something else
else:
do something else
does the "else" check the condition in "elif" or both conditions "if" and "elif"?
is there any interesting order in which they can be used (e.g. if, else, elif, else etc.) ?
thanks
else is the catch-all after all the if and elif statements were false. Putting it in the middle would be a syntax error.
Don't think of the else "checking the conditions." Think of it as the control flow never even reaches the else if the others were true. The same is true for multiple elif.
Consider this:
if False:
print 'first'
elif True:
print 'second'
elif True:
print 'third'
Even third won't print, because the second one was true. It doesn't matter that the third was true, because it's not even evaluated.
This can have some side effects too, if you're calling functions:
if send_email(to_coworker):
pass
elif send_email(to_boss):
pass
Assuming the function returns True if it succeeds, the email to your boss will only send if the email to your coworker fails, even though the function would need to be called to evaluate the elif condition
They're processed in the order that they're encountered in the file.
if True:
# Always executes.
elif False:
# Is never checked.
else:
# We never get this far, either.
As soon as the first condition that evaluates True is encountered the corresponding block of code is executed. Additional conditions aren't checked.
They don't have priorities for itself, what really matters is the order, so the first condition will be checked and if the first condition is False than the second condition is checked and so on until any condition is True or it executes the else statement if and only if all conditions where False
In your example if conditionA is True then the code inside the if statement will be executed and the elif and else conditions will not matter at all.
If conditionA is False and conditionB is True than the code inside the elif statement will be executed.
Finally only when the conditionA and conditionB is False then the code inside else block will be executed

How "yes" inside the ELSE get printed when there is no IF statement for to that else?

How this "yes" getting printed?? hello will be printed once(for i==3) but print("yes")
giving no error even there is no if statement for that else.
CODE:
for i in range(5):
if i == 3:
print("hello")
else:
print("yes")
The else branch of a for loop is always executed unless the loop was broken out of (with a break). Quoting the for statement documentation:
When the items are exhausted (which is immediately when the sequence is empty), the suite in 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.
If you wanted the else to be part of the if statement, indent it to the same level:
for i in range(5):
if i == 3:
print("hello")
else:
print("yes")
and it'll be executed for every iteration except where i == 3 is true.

Flow control after breaking out of while loop in Python

I am pretty new to both programming and Python. A few times now, I have created what feels like an awkward program flow, and I am wondering if I am following best practices. This is conceptually what I have wanted to do:
def pseudocode():
while some condition is true:
do some stuff
if a condition is met:
break out of the while loop
now do a thing once, but only if you never broke out of the loop above
What I've ended up doing works, but feels off somehow:
def pseudocode():
while some condition is true:
do some stuff
if some condition is met:
some_condition_met = True
break out of the while loop
if some_condition_met is False:
do a thing
Is there a better way?
You're looking for while-else loop:
def pseudocode():
while some condition is true:
do some stuff
if a condition is met:
break out of the while loop
else:
now do a thing once, but only if you never broke out of the loop above
From docs:
while_stmt ::= "while" expression ":" suite
["else" ":" suite]
A break statement executed in the first suite terminates the loop
without executing the else clause’s suite.
Use an else clause to the while loop:
while some_condition:
do_stuff()
if a_condition_is_met:
break
else:
executed_when_never_broken
See the while statement documentation:
A break statement executed in the first suite terminates the loop without executing the else clause’s suite.
If you think about it, you might already have a perfectly good condition to use without setting a flag: the condition at the top of the while loop (or, rather, the not of it). Assuming you don't change the truthiness of your condition during the same iteration as a break, this gives you:
while something:
do_stuff()
if something_else:
break
if not something:
more_stuff()
This makes sense if you think of while as a repeated if: instead of happening once, a while keeps going until the condition becomes falsey.
But, like the other answers have mentioned, the analogy goes further: just like you don't have to spell all your ifs as
if a:
a_stuff()
if not a:
b_stuff()
while accepts an else that is executed if the condition at the top is tested and found to be falsey. So,
while something:
do_stuff()
if something_else:
break
else:
more_stuff()
And, same as the if/else case, this doesn't imply any further tests of the condition than what would happen anyway. In the same way that an else attached to if a won't run if the true-branch makes a falsey, an else attached to a while will never run after a break since that explicitly skips ever checking the condition again. This makes the else: equivalent to a decicated flag in every case.
This also extends to for loops, even though the analogy breaks - but it executes under similar enough rules: the else is run if the loop ends by having run its course rather than hitting a break.

Python: 'break' outside loop

in the following python code:
narg=len(sys.argv)
print "#length arg= ", narg
if narg == 1:
print "#Usage: input_filename nelements nintervals"
break
I get:
SyntaxError: 'break' outside loop
Why?
Because break cannot be used to break out of an if - it can only break out of loops. That's the way Python (and most other languages) are specified to behave.
What are you trying to do? Perhaps you should use sys.exit() or return instead?
break breaks out of a loop, not an if statement, as others have pointed out. The motivation for this isn't too hard to see; think about code like
for item in some_iterable:
...
if break_condition():
break
The break would be pretty useless if it terminated the if block rather than terminated the loop -- terminating a loop conditionally is the exact thing break is used for.
Because break can only be used inside a loop.
It is used to break out of a loop (stop the loop).
Because the break statement is intended to break out of loops. You don't need to break out of an if statement - it just ends at the end.
This is an old question, but if you wanted to break out of an if statement, you could do:
while 1:
if blah:
break

Categories

Resources