简体   繁体   中英

Python if/else loop not working

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

However, I am trying to make it so that at the command line, I can enter one of the column headers in the csv file and the code will only make a graph of the specified command. Example: python histogram_maker.py "C:/Folder" Area.

I was able to do that, but I want to add a part that would create an error message in case the user enters a command that is not specified in the csv file. Example: Perimeter does not exist. What is wrong with my code? Even if something exists I get "does not exist" 20 times on the command prompt, but it still makes all the files that I need. How do I stop this repetition and make it so that the error only comes up if something is not in the csv file.

        for column in df:
            os.chdir(directory)
            if len(sys.argv)>2:
                for x in arguments:
                    if x.endswith(column):
                       #code for histogram
                    else: 
                        print "does not exist"

You are testing all the arguments, even if there is only one that matches. For each argument that doesn't match, you print your error message.

Use the any() function to see if there are any matches:

if len(sys.argv)>2:
    if any(x.endswith(column) for x in arguments):
        #code for histogram
    else: 
        print "does not exist"

or invert the test; use not and bail out early:

if len(sys.argv)>2:
    if not any(x.endswith(column) for x in arguments):
        print "does not exist"
        sys.exit(1)

    #code for histogram

If any() with a generator expression is a little too hard to grok, you can still use a for loop, but you need to use break to end the loop early and a else: suite that'll be executed when the for loop was not exited early:

for x in arguments:
    if x.endswidth(column):
        break  # found a match
else:
    # `for` loop was not exited, so no match found
    print "does not exist"
    sys.exit(1)

Maybe you want something like this....

    for column in df:
        os.chdir(directory)
        if len(sys.argv)>2:
            found = False
            for x in arguments:
                if x.endswith(column):
                   found = True
                   #code for histogram
                   break
            if (found == False):
                print "does not exist"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM