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

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.

Related

Continue the loop after an exception used in python

I am trying to run a loop with try and exception in python. Initially it runs for p=0 and j=1,2 then falls into the exception. the problem is that then I would like the loop to continue for p=1 and j=1,2,2....can you help me thanks! I tried something like this but it's not working
for p in range(1):
for j in range(23):
try:
b = response_json[0]['countries'][p]['names'][j]['values']
except:
break
Overall, using exceptions to handle normal flow is a bad pattern. Exceptions are for, well, exceptions.
Looks like you are trying to iterate over an array with missing keys. Instead of trying each key, you could iterate over the collection directly
country_data = response_json[0]['countries']
for country in country_data:
for name in country['names']:
b = name['values']
Replace break with continue (or pass).
break jumps to the end of the loop, continue jumps back to the start to continue with the next iteration. pass is a no-op used when a block is empty.

startswith() function not working in while loop but works in for loop? python

not working while-loop
i=0
l1=["rohan","sachin","sam","raj"]
while i<len(l1):
if l1[i].startswith('s'): #if i comment out this line it is working
print("GREET "+l1[i])
i=i+1
That is because incrementing of i is done inside if condition instead of while loop. As first word in your list did not start with "S" it wont go inside if hence i is not incremented and while loop executes forever. it is just a logic issue
Indentation is important in Python.
You must increment your counter i every time, not just when you print, otherwise it's an endless loop.
i=0
l1=["rohan","sachin","sam","raj"]
while i<len(l1):
if l1[i].startswith('s'):
print("GREET "+l1[i])
i=i+1 # <- increment counter outside of if-block!
yes ,after shifting counter to left it is working. counter should be placed out side of if block.

What is this condition testing? [duplicate]

This question already has answers here:
What does "while True" mean in Python?
(18 answers)
Closed 9 years ago.
in the following program:
count = 0
while True:
count += 1
if count>10:
break
if count==5:
continue
print(count)
what exactly is while True testing? And can there ever be a while false condition, if so what would that be testing?
while True: is an infinite loop. It will only ever be broken by break, return, or an exception being raised (in your case the first).
It is an infinite loop. It tests if True is.. true, which it always is.
It is the conditions in the loop that end it; the break statement breaks out of the infinite loop here, not the while condition.
Note that the continue statement merely skips the remainder of the loop iteration and skips to the next.
Other events that'd end the loop are a return (provided the loop is part of a function), or an if an exception was raised.
This will create an infinite loop, most likely causing your program to crash. If you would like to stop the loop, use return. You're code is pretty much counting up to 10, then stopping, as seen in
if count>10:
break
a better way of doing this would be to use a for loop
for count in range(0, 10):

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.

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