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.

2 Answers 2

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".)

Sign up to request clarification or add additional context in comments.

5 Comments

what does itertools.count() do?
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 . In this case the stream is infinite, and we break the loop with the sentinel value.
sounds like a pretty big workaround to make a for loop sentinel-controlled.
I didn't say it was a good idea, I just showed you one way it is possible :-)
yup exactly what i needed to see.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.