Break statement in Python
Question: 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?


Answer: I'm guessing, based on your [previous
question](http://stackoverflow.com/questions/9039320/getting-arguments-from-
command-line-python), 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](http://docs.python.org/library/stdtypes.html#comparisons) 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.

