Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 3.1 boolean check with for loop

Tags:

python

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.

like image 271
Pinsickle Avatar asked Oct 12 '25 23:10

Pinsickle


1 Answers

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
like image 197
Zeke Avatar answered Oct 16 '25 06:10

Zeke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!