frazman
frazman

Reputation: 33243

Break statement in Python

I am trying to break out of a for loop, but for some reason the following doesn't work as expected:

for out in dbOutPut:
    case_id = out['case_id']
    string = out['subject']
    vectorspace = create_vector_space_model(case_id, string, tfidf_dict)
    vectorspace_list.append(vectorspace)
    case_id_list.append(case_id)

    print len(case_id_list)

    if len(case_id_list) >= kcount:
        print "true"
        break

It just keeps iterating untill the end of dbOutput. What am I doing wrong?

Upvotes: 0

Views: 233

Answers (2)

unutbu
unutbu

Reputation: 879611

I'm guessing, based on your previous question, that kcount is a string, not an int. Note that when you compare an int with a string, (in CPython version 2) the int is always less than the string because 'int' comes before 'str' in alphabetic order:

In [12]: 100 >= '2'
Out[12]: False

If kcount is a string, then the solution is add a type to the argparse argument:

import argparse
parser=argparse.ArgumentParser()
parser.add_argument('-k', type = int, help = 'number of clusters')
args=parser.parse_args()
print(type(args.k))   
print(args.k)

running

% test.py -k 2

yields

<type 'int'>
2

This confusing error would not arise in Python3. There, comparing an int and a str raises a TypeError.

Upvotes: 6

Li0liQ
Li0liQ

Reputation: 11264

Could it happen that kcount is actually a string, not an integer and, therefore, could never become less than any integer?
See string to int comparison in python question for more details.

Upvotes: 4

Related Questions