Python: 'break' outside loop - python

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

Related

Excepting Breaks In Python

I know this sounds crazy, but I couldn't find a solution. I was trying to except the break statement inside a loop using try-except.
Here is what I tried:
for i in range(10):
try:
print(i)
break
except break:
print("Break excepted")
pass
But Python3.x returns the Error:
SyntaxError: invalid syntax
So how do I except the break statement?
Ps: I know I could have the print statement before the break and avoid break statement, but if case I want to, how would I?
You cannot add a break exception because break is not an exception.
Also with the flow of operations, if the loop cannot run, your print(i) will not get executed and so the code will not reach the break statement anyways.
If you're trying to find at which loop the code breaks, your code should work without needing the break too.
for i in range(10):
try #try running the loop
print(i)
except: #if the loop breaks
print("Break excepted") #print this and continue loop
Because the try is inside the for-loop; when there is an exception, the loop will still continue with the next iteration.
You can of course, also catch more specific exceptions like except IndexError or except KeyError. The full list of exceptions is available in the documentation.

Python simplify if and loop

Our code reviewer is telling me that flag in the code below is bad and I need to refactor code in a "Python-like" style. I really can't understand how I can avoid this flag usage, here is a sample of code:
flag = false
for (i in range(2,4)):
zoom()
if (check_condition()):
flag = true
break
if (flag):
tap()
else:
raise Exception("failed")
I can see the only way to make a tap inside if. In this case I will have to add a return statement inside a loop, which is not the best idea from the code style point of view, isn't it?
So maybe someone can suggest a better way to organize this code?
You can use an else: statement with the for statement. It's only executed if the loop finishes normally, instead of exiting with break
for i in range(2, 4):
zoom()
if check_condition():
break
else:
raise Exception("failed")
tap()
I don't think you need the falg here either, if you just call the tab() method instead of changing the flag value to true. It will work the same.
for (i in range(2,4)):
zoom()
if (check_condition()):
tab()
break
else:
raise Exception("failed")

How else part work in continue statement?

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.

What's the difference between pass and continue in python [duplicate]

This question already has answers here:
Is there a difference between "pass" and "continue" in a for loop in Python?
(13 answers)
Closed 5 years ago.
My test shows that both pass and continue can be used equivalently to construct a empty for-loop for test purpose. Are there any difference between them?
The pass keyword is a "no-operation" keyword. It does exactly nothing. It's often used as a placeholder for code which will be added later:
if response == "yes":
pass # add "yes" code later.
The continue keyword, on the other hand, is used to restart a loop at the control point, such as with:
for i in range(10):
if i % 2 == 0:
continue
print(i)
That loop will only output the odd numbers since continue returns to the loop control statement (for) for iterations where i is even.
Contrast that with the exact same code, but using pass in place of continue:
for i in range(10):
if i % 2 == 0:
pass
print(i)
That loop prints all the numbers in the range, since pass does not return to the loop control statement for even (or any) values of i. It simply drops through to the print statement.
In terms of an empty for loop, you're correct that they're functionally identical. You can use either of:
for i in range(10):
pass
for i in range(10):
continue
pass does nothing (no operation), while continue make control flow to continue to next cycle of the loop.
If the loop contains only a single statement, a pass or continue won't make any difference. But if there are multiple statements, then it matters:
for item in my_list:
pass
print(item) #This will be executed
for item in my_list:
continue
print(item) #won't be executed
Basically, the pass statement do nothing, while the continue statement will restart the loop.
But in your case:
for item in my_list:
pass
#Since there's nothing after pass, the loop is finished.
for item in my_list:
continue
#You're restarting the loop
There difference is not very visible.
Hope this helps!
continue means "skip to the end of the loop body". If it's a while loop, the loop continues on to the loop test; if it's a for loop, the loop continues on to the next element of whatever it's iterating over.
pass does absolutely nothing. It exists because you have to have something in the body of an empty block statement, and pass is more readable than executing 1 or None as a statement for that purpose.
This will lead to an infinite loop if you use continue:
i = 0
while i<1:
continue
i = i + 1
print i
because continue only goes to the next iteration. But pass will work for this case.
pass and continue both work, but may create infinite loops.
For example, the following code will create infinite loop.
i = 0
while i<100:
continue # replacing continue with pass still creates an infinite loop.
If you want to avoid this (perhaps you intend to modify i withe loop, but you haven't written the code yet), use break.

Python "While" Loops and Breaking Them

If I have two while: loops, one inside of the other, like such:
while #test :
while #test :
#other code
if #test :
break
#other code
Will the break stop both while: loops or only the one where the if #test : is in?
Thanks for the help!
It would only stop the inner loop. If you wanted to break both loops, you'd have to provide another condition to break in the outer loop.
A break always breaks only the loop enclosing it, so the last line of the code will be executed under the outer loop.
Learn more
From python documentation:
break may only occur syntactically nested in a for or while loop, but
not nested in a function or class definition within that loop.
It terminates the nearest enclosing loop, skipping the optional else
clause if the loop has one.
"break terminates the nearest eclosing loop" - e.g. only inner while
break only stop the one where the if #test,so the other code will be exec.

Categories

Resources