Home > Software design >  How do I use a while loop when dealing with an input that could raise an exception?
How do I use a while loop when dealing with an input that could raise an exception?

Time:04-09

I'm working on code for my uni project and this one part requires the user to input a file name, and while the file name is not found, it should display a message and then prompt the user to display a valid filename. This is what I have so far but it stops after a second invalid input and I'm not sure how to use a while loop with this. If someone could help, that would be great. Thank you!

if user_choice == commands[2]: 
    try:
        file_name = input("Enter file name: ")
        print(INPUT(file_name))

    except FileNotFoundError:
        print("The file name you entered does not exist.")
        file_name = input("Enter file name: ")

CodePudding user response:

You can just create a while loop and break when the file is found. so it would be something like this:

if user_choice == commands[2]: 
    while True:
        try:
            file_name = input("Enter file name: ")
            print(INPUT(file_name))
            #if the file is found (if statement) (I don't know how you would do this as i haven't seen the full code):
                break

        except FileNotFoundError:
            print("The file name you entered does not exist.")
            file_name = input("Enter file name: ")

CodePudding user response:

Try something like this :

if user_choice == commands[2]: 

var = 0
while var != 1 :
  try:
        file_name = input("Enter file name: ")
        print(INPUT(file_name))
        var = 1

    except FileNotFoundError:
        print("The file name you entered does not exist.")
        file_name = input("Enter file name: ")

  • Related