This question already has answers here:
How can I make a function that will called from inside a loop and that will indicate whether to continue?
(2 answers)
Closed 13 days ago.
Here i created some function like
def common_function():
if i==3:
continue
and
for i in range(0,10):
common_function(i)
this is simple example, In my code i create common function later i want to used that on multiple place but this cannot be applied.
Is there any way to do that..
If you want to continue a for-loop in certain situations, you can use this code snippet:
def action_inside_loop(i):
if i == 3:
return
print(f'Doing something with index {i}')
for i in range(5):
action_inside_loop(i)
This results in the output:
Doing something with index 0
Doing something with index 1
Doing something with index 2
Doing something with index 4
If on the other hand, you want to break out of a for-loop in certain situations, you can use this code snippet:
def action_inside_loop(i):
if i == 3:
return False
print(f'Doing something with index {i}')
return True
for i in range(5):
should_continue = action_inside_loop(i)
if not should_continue:
break
This results in the output:
Doing something with index 0
Doing something with index 1
Doing something with index 2
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..."
Many beginners accidentally stumble on this syntax when they try to put an if/else block inside of a while or for loop, and don't indent the else properly. The solution is to make sure the else block lines up with the if, assuming that it was your intent to pair them. This question explains why it didn't cause a syntax error, and what the resulting code means. See also I'm getting an IndentationError. How do I fix it?, for the cases where there is a syntax error reported.
The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won't be executed.
One way to think about it is as an if/else construct with respect to the condition:
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 might 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()
The else clause is executed if you exit a block normally, by hitting the loop condition or falling off the bottom of a try block. It is not executed if you break or return out of a block, or raise an exception. It works for not only while and for loops, but also try blocks.
You typically find it in places where normally you would exit a loop early, and running off the end of the loop is an unexpected/unusual occasion. For example, if you're looping through a list looking for a value:
for value in values:
if value == 5:
print "Found it!"
break
else:
print "Nowhere to be found. :-("
Allow me to give an example on why to use this else-clause. But:
my point is now better explained in Leo’s answer
I use a for- instead of a while-loop, but else works similar (executes unless break was encountered)
there are better ways to do this (e.g. wrapping it into a function or raising an exception)
Breaking out of multiple levels of looping
Here is how it works: the outer loop has a break at the end, so it would only be executed once. However, if the inner loop completes (finds no divisor), then it reaches the else statement and the outer break is never reached. This way, a break in the inner loop will break out of both loops, rather than just one.
for k in [2, 3, 5, 7, 11, 13, 17, 25]:
for m in range(2, 10):
if k == m:
continue
print 'trying %s %% %s' % (k, m)
if k % m == 0:
print 'found a divisor: %d %% %d; breaking out of loop' % (k, m)
break
else:
continue
print 'breaking another level of loop'
break
else:
print 'no divisor could be found!'
The else-clause is executed when the while-condition evaluates to false.
From the documentation:
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.
The else clause is only executed when the while-condition becomes false.
Here are some examples:
Example 1: Initially the condition is false, so else-clause is executed.
i = 99999999
while i < 5:
print(i)
i += 1
else:
print('this')
OUTPUT:
this
Example 2: The while-condition i < 5 never became false because i == 3 breaks the loop, so else-clause was not executed.
i = 0
while i < 5:
print(i)
if i == 3:
break
i += 1
else:
print('this')
OUTPUT:
0
1
2
3
Example 3: The while-condition i < 5 became false when i was 5, so else-clause was executed.
i = 0
while i < 5:
print(i)
i += 1
else:
print('this')
OUTPUT:
0
1
2
3
4
this
My answer will focus on WHEN we can use while/for-else.
At the first glance, it seems there is no different when using
while CONDITION:
EXPRESSIONS
print 'ELSE'
print 'The next statement'
and
while CONDITION:
EXPRESSIONS
else:
print 'ELSE'
print 'The next statement'
Because the print 'ELSE' statement seems always executed in both cases (both when the while loop finished or not run).
Then, it's only different when the statement print 'ELSE' will not be executed.
It's when there is a breakinside the code block under while
In [17]: i = 0
In [18]: while i < 5:
print i
if i == 2:
break
i = i +1
else:
print 'ELSE'
print 'The next statement'
....:
0
1
2
The next statement
If differ to:
In [19]: i = 0
In [20]: while i < 5:
print i
if i == 2:
break
i = i +1
print 'ELSE'
print 'The next statement'
....:
0
1
2
ELSE
The next statement
return is not in this category, because it does the same effect for two above cases.
exception raise also does not cause difference, because when it raises, where the next code will be executed is in exception handler (except block), the code in else clause or right after the while clause will not be executed.
I know this is old question but...
As Raymond Hettinger said, it should be called while/no_break instead of while/else.
I find it easy to understeand if you look at this snippet.
n = 5
while n > 0:
print n
n -= 1
if n == 2:
break
if n == 0:
print n
Now instead of checking condition after while loop we can swap it with else and get rid of that check.
n = 5
while n > 0:
print n
n -= 1
if n == 2:
break
else: # read it as "no_break"
print n
I always read it as while/no_break to understand the code and that syntax makes much more sense to me.
thing = 'hay'
while thing:
if thing == 'needle':
print('I found it!!') # wrap up for break
break
thing = haystack.next()
else:
print('I did not find it.') # wrap up for no-break
The possibly unfortunately named else-clause is your place to wrap up from loop-exhaustion without break.
You can get by without it if
you break with return or raise → the entire code after the call or try is your no-break place
you set a default before while (e.g. found = False)
but it might hide bugs the else-clause knows to avoid
If you use a multi-break with non-trivial wrap-up, you should use a simple assignment before break, an else-clause assignment for no-break, and an if-elif-else or match-case to avoid repeating non-trival break handling code.
Note: the same applies to for thing in haystack:
Else is executed if while loop did not break.
I kinda like to think of it with a 'runner' metaphor.
The "else" is like crossing the finish line, irrelevant of whether you started at the beginning or end of the track. "else" is only not executed if you break somewhere in between.
runner_at = 0 # or 10 makes no difference, if unlucky_sector is not 0-10
unlucky_sector = 6
while runner_at < 10:
print("Runner at: ", runner_at)
if runner_at == unlucky_sector:
print("Runner fell and broke his foot. Will not reach finish.")
break
runner_at += 1
else:
print("Runner has finished the race!") # Not executed if runner broke his foot.
Main use cases is using this breaking out of nested loops or if you want to run some statements only if loop didn't break somewhere (think of breaking being an unusual situation).
For example, the following is a mechanism on how to break out of an inner loop without using variables or try/catch:
for i in [1,2,3]:
for j in ['a', 'unlucky', 'c']:
print(i, j)
if j == 'unlucky':
break
else:
continue # Only executed if inner loop didn't break.
break # This is only reached if inner loop 'breaked' out since continue didn't run.
print("Finished")
# 1 a
# 1 b
# Finished
The else: statement is executed when and only when the while loop no longer meets its condition (in your example, when n != 0 is false).
So the output would be this:
5
4
3
2
1
what the...
Suppose you've to search an element x in a single linked list
def search(self, x):
position = 1
p =self.start
while p is not None:
if p.info == x:
print(x, " is at position ", position)
return True
position += 1
p = p.link
else:
print(x, "not found in list")
return False
So if while conditions fails else will execute, hope it helps!
The better use of 'while: else:' construction in Python should be if no loop is executed in 'while' then the 'else' statement is executed. The way it works today doesn't make sense because you can use the code below with the same results...
n = 5
while n != 0:
print n
n -= 1
print "what the..."
As far as I know the main reason for adding else to loops in any language is in cases when the iterator is not on in your control. Imagine the iterator is on a server and you just give it a signal to fetch the next 100 records of data. You want the loop to go on as long as the length of the data received is 100. If it is less, you need it to go one more times and then end it. There are many other situations where you have no control over the last iteration. Having the option to add an else in these cases makes everything much easier.
I have a for loop that I'm needing to break if there is an error.
I want to be able to continue a for loop if a boolean is true. But don't want to have to write an "if" statement over and over again. Is it possible to call "continue" outside of a "loop"?
The following code results in an error. But is my thinking of this would work.
_Range = 6
_RangeEnd = 0
def function_to_call():
print("x")
if _Continue is True:
continue
for x in range(_Range):
_RangeEnd = _RangeEnd + 1
function_to_call()
if _RangeEnd == 5:
_Continue = True
If this isn't possible. What would be an efficient way to do this? I'm reusing this function in a good number of different for loops.
You can't call continue outside of a loop, e.g. from a function called from inside a loop.
One option is to return a meaningful value from your function that tells the caller to continue, i.e. some truthy value or falsy value:
def function_that_decides_to_continue():
print("x")
return your_condition_here
for x in range(_Range):
if function_that_decides_to_continue():
continue # skip extra stuff
# do extra stuff
Or a sentinel object:
CONTINUE = object() # sentinel object, whose sole purpose is to be uniquely identifiable
def function_that_decides_to_continue():
print("x")
if your_condition_here:
return CONTINUE
for x in range(_Range):
if function_that_decides_to_continue() is CONTINUE:
continue
Another option in an error-handling use-case is directly handling those exceptions with try/except:
def function_that_may_fail(divisor):
return 10 / divisor
for x in [2, 5, 0, 1]:
try:
result = function_that_may_fail(x)
except ZeroDivisionError:
continue
do_stuff_with(result)
Though I admit I might be misinterpreting what you actually want to do, because perhaps the most straightforward "want to be able to continue a for loop if a boolean is true" is just a plain while:
while function_that_decides_to_continue():
# do stuff
You'll have to provide actual examples of the "different for loops" you wanted your "function that continues" will be used in.
While I am in doubt this is a good idea for the flow control of the program, something like this can simulate what you need:
_Range = 6
_RangeEnd = 0
class Continue(Exception):
pass
def function_to_call():
print("x")
if _Continue is True:
raise Continue
for x in ...:
try:
function_to_call()
something_else()
except Continue:
continue
And no, continue can't be outside the loop.
The continue needs to be inside a loop, I think the best solution would be to put a (if boolVar == True: continue) inside the for.
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed last year.
I am trying this code.
Function incre_test is recursive unless it satisfy the condition.
I expect 5 as result but it returns None.
What is the best practice for this pattern?
def incre_test(i):
if i > 4:
return i
i = i + 1
incre_test(i)
res = incre_test(0)
print(res) // why None???
Try this:
def incre_test(i):
while not i == 5:
i+=1
return i
res = incre_test(0)
print(res)
You have to use a while <bool>: loop to run a script (in this case i+=1) until the condition given is true.
Using a loop inside the function might do you better
such as
def incre_test(i):
while i < 5:
i += 1
return i
It's because your function is not returning anyting unless the parameter is greater than 4, so all you have to do is to add a return statement over the recursive call of the function, like this...
def incre_test(i):
if i > 4:
return i
return incre_test(i+1)
res = incre_test(0)
print(res)
Output:-
5
def hi (n):
if n<=5:
print("we are inside hi")
n+=1
return n
n=1
hi(n)
1) In the above code i have declared a function hi() which takes an input n
2)I want to iterate inside the if condition until n is less than 5,totally execute the print statement 4 times
3)But it is not working after execution of one time inside the condition
4)I am thinking i have given return statement for if condition but the function is totally being exit
5)(i am thinking i am returning the n value to the if condition and it checks the condition and it will iterate ) if wrong correct me
Not sure exactly what you want to achieve, but based on the info you have provided:
def hi (n):
while (n < 5):
print("we are inside hi")
n -= 1
Briefly speaking, using return inside a function means to return the value that is followed or return None if there is no value. In addition, the execution of the function is terminated just after the return statement is executed.
You can use the return statement, but if you want to iterate it is not correct because your function will terminate its execution. Also remember that once you execute the iteration of the loop, there won't be more statements to execute inside your function which means an implicit return statement will be executed which returns None, and again function ends execution.
You need a loop for this. Try this instead
for _ in range(4):
print("we are inside hi")
Of course, you need a loop to make iteration. If you just want to print the statement 4 times, simply make a range of loop.
def hi ():
for n in range(4):
print(n+1," we are inside hi")
hi()
you can use this:
def hi (n):
while n <= 5:
print("we are inside hi")
n+=1
return n
n=1
hi(n)
you need a loop to iterate and return statement will exit from the function call.