This question already has answers here:
Why doesn't exec("break") work inside a while loop
(6 answers)
Closed 3 years ago.
A recent question made me think if it is possible to do something like:
def defA(flag) :
return "value = 'yes'" if flag else "continue"
flag = False
#n can be a reasonable number like 100
for x in range(n):
#some logic that may change the flag
exec(defA(flag))
here, you got a variable assignment if the flag is true, or continue the for loop otherwise, but it gives me an odd error:
SyntaxError: 'continue' not properly in loop
Is it possible or should I let it go?
Because exec doesn't carry the context over to the statement being executed.
pass can be used anywhere, so the context doesn't matter. continue can only be used in the context of a loop, but that context is not available to exec.
You can only use continue in an exec statement if the loop itself is also part of the executed code:
f = 'for x in range(n): if(flag) continue' exec f
In other words, you can only use exec for complete statements, where a single continue (or break) is not complete.
Related
The title might be misleading, so here is a better explanation.
Consider the following code:
def minimum_working_environment(r):
trial=np.arange(0,6)[::-1]
for i in range(len(trial)):
if r>trial[i]:
return i
return len(trial)
We see that if r is smaller than the smallest element of trial, the if clause inside the loop is never executed. Therefore, the function never returns anything in the loop and returns something in the last line. If the if clause inside the loop is executed, return terminates the code, so the last line is never executed.
I want to implement something similar, but without return, i.e.,
def minimum_working_environment(self,r):
self.trial=np.arange(0,6)[::-1]
for i in range(len(self.trial)):
if r>trial[i]:
self.some_aspect=i
break
self.some_aspect=len(self.trial)
Here, break disrupts the loop but the function is not terminated.
The solutions I can think of are:
Replace break with return 0 and not check the return value of the function.
Use a flag variable.
Expand the self.trial array with a very small negative number, like -1e99.
First method looks good, I will probably implement it if I don't get any answer. The second one is very boring. The third one is not just boring but also might cause performance problems.
My questions are:
Is there a reserved word like return that would work in the way that I want, i.e., terminate the function?
If not, what is the best solution to this?
Thanks!
You can check that a for loop did not run into a break with else, which seems to be what you're after.
import numpy as np
def minimum_working_environment(r):
trial = np.arange(0, 6)[::-1]
for i in range(len(trial)):
if r > trial[i]:
return i
return len(trial)
def alternative(r):
trial = np.arange(0, 6)[::-1]
for i in range(len(trial)):
if r > trial[i]:
break
else:
i = len(trial)
return i
print(minimum_working_environment(3))
print(minimum_working_environment(-3))
print(alternative(3))
print(alternative(-3))
Result:
3
6
3
6
This works because the loop controlling variable i will still have the last value it had in the loop after the break and the else will only be executed if the break never executes.
However, if you just want to terminate a function, you should use return. The example I provided is mainly useful if you do indeed need to know if a loop completed fully (i.e. without breaking) or if it terminated early. It works for your example, which I assume was exactly that, just an example.
This question already has answers here:
Why does python use 'else' after for and while loops?
(24 answers)
Closed 3 years ago.
I already have a lot of experience in Python, but recently I've seen some people using else at the end of a while or for block. I was very curious and decided to test:
for i in range(2):
print(i)
else:
print("Something...")
Output:
0
1
Something...
Using or not else, the code will execute the same way, so what's the use of this?
else after a for or while block will execute if and only if the block terminates normally. If you leave through a break or exception, that else block gets skipped.
for i in range(2):
print(i)
break
else:
print("Something...")
Output:
0
This question already has answers here:
Else clause on Python while statement
(13 answers)
Closed 7 years ago.
I was going through this. Coming from C environment, it hit me right in the face with utter surprise and disbelief. And, then I tried it for myself::
bCondition = True
while bCondition:
print("Inside while\n")
bCondition = False
else:
print("Inside else\n")
print("done\n")
This code renders the below output,
#Output
Inside while
Inside else
done
Ideone link
Now, my question is, Why? why do we need this? Why both the blocks are executed? Isn't if and else were made for each other, then what use case will make this design a useful design to implement?
Again if we just change the code to incorporate a break, the behavior is more mysterious. Ideone Link.
bCondition = True
while bCondition:
break
else:
print("Inside else\n")
print("done\n")
This code renders the below output,
#Output
done
Why both of the blocks are skipped? Isn't break made to break out of the loop only, then why is it breaking out of the else block?
I went through the documentation too, couldn't clear my doubts though.
The use of the else clause after a loop in python is to check whether some object satisfied some given condition or not.
If you are implementing search loops, then the else clause is executed at the end of the loop if the loop is not terminated abruptly using constructs like break because it is assumed that if break is used the search condition was met.
Hence when you use break, the else clause is not evaluated. However when you come out of the loop naturally after the while condition evaluates to false, the else clause is evaluated because in this case it is assumed that no object matched your search criteria.
for x in data:
if meets_condition(x):
print "found %s" % x
break
else:
print "not found"
# raise error or do additional processing
This question already has answers here:
python print done after while
(4 answers)
Closed 7 years ago.
li=['ram', 12, 13, 'shyam']
>>> for i in li:
... print(i)
... print("hi")
File "<stdin>", line 3
print("hi")
^
SyntaxError: invalid syntax
I'm working on Ubuntu shell with Python-1.7.2 and trying to simply loop through a list and want to add a print statement at the end. But it raises exception as above.
I don't be able to understand why it raise above exception. As for loop reaches it's end and I simply add a print statement outside for loop.
Please! help me to figure out what's going wrong?
After completing the block, you have to press Enter one more time.
When running in interactive interpreter, you need to leave an empty line after a block to indicate the end of the block, otherwise the interpreter assumes that the lines that come after the block are part of the block, and through the invalid syntax error (Like it did in your case).
Example -
>>> for i in li:
... print(i)
... # <---- notice the empty line
>>> print("hi")
This question already has answers here:
Why does python use 'else' after for and while loops?
(24 answers)
Closed 9 years ago.
I can run the below python script without errors.
for n in range(3):
print n
else:
print "done"
But I am puzzled about the else without a matching if.
It does not make sense.
Can some one explain why this works ?
The else clause of for and while only executes if the loop exits normally, i.e. break is never run.
for i in range(20):
print i
if i == 3:
break
else:
print 'HAHA!'
And the else clause of try only executes if no exception happened.
try:
a = 1 / 2
except ZeroDivisionError:
do_something()
else:
print '/golfclap'
The body of the else is executed after the for loop is done, but only if the for loop didn't terminate early by break statements.