开发者

python 3.1 boolean check with for loop

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

for i in range (0, someNumber) and k开发者_如何学GoeepGoing == True

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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜