Zion
Zion

Reputation: 1610

odd while loop behavior (python)

I have this code:

class CleanUp:
    def __init__(self,directory):
        self.directory = directory

    def del_items(self,*file_extensions):
        """deletes specified file extensions in specificied directory"""

        removed_files = [file for file in os.listdir(self.directory) for ext in file_extensions if ext in file]
        for index ,file in enumerate(removed_files):
            print(str(index + 1) + ": " + file + "\n")
        confirm_delete = input("are you sure you want to delete all {0} files? y|n ".format(len(removed_files)))
        while confirm_delete.lower() not in ("y","n"):<--------- this while loop
            confirm_delete = input("are you sure you want to delete all {0} files? y|n ".format(len(removed_files)))
        if confirm_delete.lower() == "y":
            for file in removed_files:
                try:
                    os.remove(os.path.join(self.directory,file))
                except:
                    pass
            print("successfully deleted {0} files".format(len(removed_files)))
        else:
            print("deletion cancelled goodbye")
            pass




directory = input("please enter a directory ")
while not os.path.exists(directory):
    print("{0} is not a valid directory \n".format(directory))
    directory = input("please enter a directory ")

file_extensions = input("please put in file extensions of files that need deleting. seperate them by one space ")
file_extensions = file_extensions.split()
desktop = CleanUp(directory)
deleted_files = desktop.del_items(*file_extensions)

This line works

while confirm_delete.lower() not in ("y","n"):

however, when I try to do

while confirm_delete.lower() != "y" or confirm_delete.lower() != "n":

the while loop never passes. I'm sure it has something to do with the or but why doesn't it work when done like that?

Upvotes: 0

Views: 44

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

Because that condition will always be true; there is no string value which is both "y" and "n" at the same time. Use and instead.

Upvotes: 3

Related Questions