0

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?

Chris
  • 44,602
  • 16
  • 137
  • 156
frazman
  • 32,081
  • 75
  • 184
  • 269
  • 1
    What is `kcount`? Please show *all* relevant parts of your code. – Greg Hewgill Jan 27 '12 at 20:56
  • hi kcount is a variable i am inputting..but its way less than the size of that list..kcount = 20...and total length of dboutput is like 100000 – frazman Jan 27 '12 at 20:57
  • 2
    Have you tried adding `print kcount` to verify condition is actually met? – Li0liQ Jan 27 '12 at 20:57
  • Does it ever print true? If not then your if statement isn't being triggered, so your break is never happening. – Herms Jan 27 '12 at 20:57
  • nopes?? it doesnt goes to that loop..though i see that length increasing? – frazman Jan 27 '12 at 20:58
  • 1
    @Fraz: I'm suggesting that your `kcount` is not an integer. It might be a string (and so Python is not doing what you expect when you compare an integer with a string). Please show the code that initialises `kcount`. – Greg Hewgill Jan 27 '12 at 20:59

2 Answers2

6

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.

Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
4

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.

Community
  • 1
  • 1
Li0liQ
  • 11,158
  • 35
  • 52