lundi 3 août 2020

Both my if and else statements are executing in Python

I'm trying to create a basic script whereby a user provides one or more paths and if that path is valid, the script proceeds.

However in my if statement, an invalid path returns both a success and failure message which will confuse the user and frankly, is confusing me.

Here is my code:

from os import path

#set a variable as False that will keep you locked in the loop until
#a valid input is provided and it is turned to True.
valid_input = False
#Start the while loop that requests user provides paths
while not valid_input:
    search_locations_str = input("Please provide the name of the loaction\nyou would like to search by inputting the\nfull path.\n \nTo search multiple locations, simply input\nmultiple paths separated by a comma and a space.")
    print("\n")
    search_locations = search_locations_str.split(", ")
    print("area(/s) to search ", search_locations)
#Add a for stament that can end the loop if, after checking the users input, 
#the paths are valid and actually exist. 
    for search_location in search_locations:
        if path.exists(search_location)==False:
            print(search_location + " not recognised, please amend or remove" )

    else:
        valid_input = True
        print(search_location + " identified, search for useful files can proceed")

If you put in a valid path, it works perfectly.

If you put in an invalid path, it tells you the path is both valid and invalid:

area(/s) to search  ['non/existent/path']
non/existent/path not recognised, please amend or remove
non/existent/path identified, search for useful files can proceed

Aucun commentaire:

Enregistrer un commentaire