0

I'm not too sure if there might have been another duplicate, but question as per topic.

The purpose of this question is not to find out whether you should or should not use for loop to implement sentinel control.

But rather to see if it can be done and hence have a better understanding of the distinction between the for and the while loop.

Calvintwr
  • 8,308
  • 5
  • 28
  • 42

2 Answers2

1

Using itertools it is possible:

>>> import itertools
>>>
>>> SENTINEL = 0
>>> for i in itertools.count():
....:    if SENTINEL >= 10:
....:        print "Sentinel value encountered! Breaking..."
....:        break
....:    
....:    SENTINEL = SENTINEL + 1
....:    print "Incrementing the sentinel value..."
....: 
Incrementing the sentinel value...
Incrementing the sentinel value...
Incrementing the sentinel value...
Incrementing the sentinel value...
Incrementing the sentinel value...
Incrementing the sentinel value...
Incrementing the sentinel value...
Incrementing the sentinel value...
Incrementing the sentinel value...
Incrementing the sentinel value...
Sentinel value encountered! Breaking...

(Inspired by stack overflow question "Looping from 1 to infinity in Python".)

Community
  • 1
  • 1
tbc
  • 1,679
  • 3
  • 21
  • 28
  • what does itertools.count() do? – Calvintwr Mar 13 '15 at 07:09
  • It returns an Iterator, which is "An object representing a stream of data. Repeated calls to the iterator’s next() method return successive items in the stream." [from python docs](https://docs.python.org/2/library/itertools.html#itertools.count) . In this case the stream is infinite, and we break the loop with the sentinel value. – tbc Mar 13 '15 at 07:27
  • sounds like a pretty big workaround to make a for loop sentinel-controlled. – Calvintwr Mar 13 '15 at 14:05
  • I didn't say it was a good idea, I just showed you one way it is possible :-) – tbc Mar 13 '15 at 20:09
  • yup exactly what i needed to see. – Calvintwr Mar 14 '15 at 01:17
0

Without importing any modules, you can also do a "sentinel" controlled looped with for by making loop to infinity and break with a condition:

infinity = [0]
sentinelValue = 1000
for i in infinity:
    if i == sentinelValue:
        break

    # like a dog chasing the tail, we move the tail...
    infinity.append(i+1)

    print('Looped', i, 'times')

print('Sentinel value reached')

Although this would create a very large infinity list that eats away at the memory.

Calvintwr
  • 8,308
  • 5
  • 28
  • 42