For Loop is not Following Indentations
<p>Afternoon all,</p>

<p>I'm encountering some strange behavior from the starred for loop below. The below function essentially iterates over the input dictionary <code>patient_features</code>, concatenating several strings to produce a SVMLight style vector. This vector is then intended to be written to the deliverables file. However, for some reason the writes at the end of the function are being called for every iteration of the starred for loop, resulting in a massive file size (and some other more minor issues). Any help on what might be causing this would be greatly appreciated.</p>

<pre><code>def save_svmlight(patient_features, mortality, op_file, op_deliverable):

    deliverable1 = open(op_file, 'wb') # feature without patient id
    deliverable2 = open(op_deliverable, 'wb') # features with patient id
    d1_line = ''
    d2_line = ''
    count = 0 # VALUE TO TEST IF INCREMENTING
    print count
    for patient_id in patient_features: #**********
        value_tuple_list = patient_features[patient_id]
        value_tuple_list.sort()
        d2_line += str(int(patient_id)) + ' '
        if patient_id in mortality:
            d1_line += str(1) + ' '
            d2_line += str(1) + ' '
        else:
            d1_line += str(0) + ' '
            d2_line += str(0) + ' '
        for value_tuple in value_tuple_list:
            d1_line += str(int(value_tuple[0])) + ":" + str("{:1.6f}".format(value_tuple[1])) + ' '
            d2_line += str(int(value_tuple[0])) + ":" + str("{:1.6f}".format(value_tuple[1])) + ' '


    count += 1
    print count # VALUE INCREMENTS WHEN IT SHOULD NOT
    deliverable1.write(d1_line); # &lt;- BEING WRITTEN TO EACH LOOP :(
    deliverable2.write(d2_line); # &lt;- BEING WRITTEN TO EACH LOOP :(
</code></pre>

<p>The issue is with using both indentations and tabs in your code. Python is not a fan if you mix the two :/</p>

<p>For future reference, if you are using Sublime Text, select all the text, and in the toolbar on top go to <code>View &gt; Indentation &gt; Convert Tabs to Spaces</code> and the issue will be resolved. </p>

<p>Thought I would save you having to manually search for each tab and replacing it :)</p>

python python-2.7 for-loop