Sourav
Sourav

Reputation: 866

Skip parts of a code inside loop if found false once

I am using OpenCV to track an object in a video frame. If the object I am tracking goes beyond ROI the codes to needs to stop recording it's current location, even if it gets back to the ROI later. However, other parts of the codes still need to continue doing their works. To simplify the problem, I am assuming a is a list, python will iterate through the list and print its index and value. If one value becomes less than 10 then the code will only print the value index only, no value. For the simple purpose, I am using the following codes.

a = [10,12,15,18,2,17,12,10,8,11]
con = True
for i in range(10):
    if con == False:
        print (i)
    else:
        print (i, a[i]) 
        if a[i]<10:
            con==False

However, it is not working and always executes the 'else' statement and provides the following result

0 10
1 12
2 15
3 18
4 2
5 17
6 12
7 10
8 8
9 11

Is there any way to get the following result -

0 10
1 12
2 15
3 18
4 2
5 
6
7
8
9

The expected output can be achived by checking the value inside the if else loop but the purpose is to stop executing a chink of code after a certain statement become False.

Upvotes: 0

Views: 48

Answers (2)

user10364045
user10364045

Reputation:

Here's another way with enumerate:

>>> a = [10,12,15,18,2,17,12,10,8,11]
>>> con = False
>>> for i, j in enumerate(a):
...     if j < 10:
...         con = True
...     if not con:
...         print(str(i) + ' ' + str(j))
...     else:
...         print(str(i))
... 
0 10
1 12
2 15
3 18
4
5
6
7
8
9

One thing that's unclear though... you still printed the 2 which was the first value to be lower than 10. Do you really want that value printed?

Upvotes: 2

sanyassh
sanyassh

Reputation: 8550

This is the problem:

con==False

It should be:

con=False

Upvotes: 2

Related Questions