user2614937
user2614937

Reputation: 45

Display an error message when argument not there

I have a directory where csv files are located. The code reads the files and creates histograms based on the data in the files.

I have made this a command prompt code where I can enter the arguments and the code will look through the csv files to see if the arguments I listed are there. I am trying to make it so that an error message comes up when I misspell a command. The following code works if the first argument is spelled correctly and the second is not, but does not display an error message if the first is misspelled and the second is correct. What's wrong?

Example: python untitled14.py "Folder" Are Perimeter DOES NOT DISPLAY ERROR MESSAGE FOR ARE BUT python untitled14.py "Folder" Perimeter Are DOES DISPLAY ERROR FOR ARE

for x in arguments:  
    found_match = False
    for column in df:
        os.chdir(directory)
        if x.endswith(column): 
            found_match = True
            #histogram code
            continue
        else:
            pass
if found_match==False: 
    print files+" " + x + " does not exist"

Upvotes: 0

Views: 106

Answers (1)

roippi
roippi

Reputation: 25964

You have unnecessary things (and some other questionable things) in your loop logic. For example, the three lines continue; else: pass do literal nothing.

The best thing to do would be to refactor your code to call a function that would return True if all the arguments validated. You didn't provide enough code for that, so I would clean the whole thing up with:

for x in arguments:  
    for column in df:
        os.chdir(directory)
        if x.endswith(column): 
            #histogram code
            break
    else:
        print "{0} {1} does not exist".format(files,x)
        break #or not, depending on what you want to do

This takes advantage of the somewhat rarely-used for/else to do something if the for loop did not break - which, in your case, is an error.

If you want to really make this re-usable, you should raise an Exception instead of just printing on an error.

Upvotes: 1

Related Questions