4

How can I add a Boolean check to a for loop? I was trying something like this:

for i in range (0, someNumber) and keepGoing == True

It is giving me the error 'bool' object is not iterable. Thanks for the help.

1 Answer 1

8

This isn't a for loop like in C; what you're doing here is creating a range object and iterating over each element in it (naming it "i") in the process. In C, you can have multiple checks during an iteration of a loop, but in Python you iterate over iterable objects such as lists or tuples.

for i in range(0, someNumber):
    if keepGoing:
        # Code

Basically, you can't set a flag to stop the loop, because the "loop" is going to iterate over the entire range object. The only way to add a "stop flag" is to break out of the loop.

for i in range(0, someNumber):
    if not keepGoing:
        break
    else:
        # Code

or even

for i in range(0, someNumber):
    if not keepGoing:
        break
    # Code
3
  • You may want to add else: break to that as well.
    – Lizzan
    Nov 22, 2010 at 6:45
  • @Pinsickle: No problem. If my answer solved your problem, click the big checkbox to accept it as the answer.
    – Zeke
    Nov 22, 2010 at 7:29
  • 3
    @Zeke Thought I'd let you know you solved my problem twice. I was messing with Python back in 2010 for a school project and haven't really used it again since then. Fast forward a year and I had student in another teaching assistant's class come to me with a similar problem. I Google the problem and I find this. I thought it was pretty funny.
    – Pinsickle
    Nov 13, 2011 at 0:10

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.