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?

6
  • 1
    What is kcount? Please show all relevant parts of your code. Commented Jan 27, 2012 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 Commented Jan 27, 2012 at 20:57
  • 2
    Have you tried adding print kcount to verify condition is actually met? Commented Jan 27, 2012 at 20:57
  • Does it ever print true? If not then your if statement isn't being triggered, so your break is never happening. Commented Jan 27, 2012 at 20:57
  • 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. Commented Jan 27, 2012 at 20:59

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.