Skip to content Skip to sidebar Skip to footer

Else Statement Does Not Return To Loop

I have a code that opens a file, calculates the median value and writes that value to a separate file. Some of the files maybe empty so I wrote the following loop to check it the f

Solution 1:

You should be using try/except blocks. Something like:

t = 15.2while t >= 11.4:
    F= r'C:\Users\Documents\bin%.2f.txt'%t 
    try:  
        F = np.loadtxt(F,skiprows=0)
        LogMass = F[:,0]
        LogRed =  F[:,1] 
        value = np.median(LogMass)  
        filesave(*find_nearest(LogMass,LogRed))
    except IndexError:
        print("bad file: {}".format(F))
    else:
        print("file worked!")
    finally:
        t -=0.2

Please refer to the official tutorial for more details about exception handling.

The issue with the last digit is due to how floats work they can not represent base10 numbers exactly. This can lead to fun things like:

In[13]: .3 * 3-.9Out[13]: -1.1102230246251565e-16

Solution 2:

To deal with the one line file case, add the ndmin parameter to np.loadtxt (review its doc):

np.loadtxt('test.npy',ndmin=2)
# array([[ 1.,  2.]])

Solution 3:

With the help of a user named ajcr, found the problem was that ndim=2 should have been used in numpy.loadtxt() to insure that the array always 2 has dimensions.

Solution 4:

Python uses indentation to define ifwhile and for blocks.

It doesn't look like your ifelse statement is fully indented from the while.

I usually use a full 'tab' keyboard key to indent instead of 'spaces'

Post a Comment for "Else Statement Does Not Return To Loop"