Is there an elegant way in Python to detect whether a break condition was engaged at the last iteration or never at all?
C++ example:
int k, n = 10;
for (k = 0; k < n; k++)
if (condition) break;
if (k == n) cout << "Never broke\n";
else cout << "Broke at " << k << '\n';
Python example:
n = 10
for k in range(n):
if condition: break
if k == n: print("Never broke")
else: print("Broke at", k)
In Python, we don't know whether condition
was true at the last iteration since k is 9 in both cases.
Why not just use range(n + 1)
instead? Because on some contexts, we might get an "index out of range" error when k is n.
One possible workaround is to use a sentinel value as shown below, but is there a better way?
n, flag = 10, True
for k in range(n):
if condition:
flag = False
break
if flag: print("Never broke")
else: print("Broke at", k)
Use for
/else
. That's specifically what it's for.
for k in range(n):
if condition:
print("Broke at", k)
break
else:
print("Never broke")