简体   繁体   中英

Python: Catching IndexError in user input

Having trouble getting my input to catch index errors regarding a function that searches list. Below is my code

    while True:
    try:
        mark_visited = int(input("Enter the number of a place to mark as visited \n>>> ")) - 1
        break
    except ValueError:
        print("Invalid input, enter a valid number")
    except IndexError:
        print("Invalid place number")

When entering an input outside of the index, I get the following error:

Traceback (most recent call last):
File "*****", line 
146, in <module>
 main()
File "*****", line 
127, in main
 mark_visited(data)
File "*****", line 
81, in mark_visited
 if data[mark_visited][3] == "v":
IndexError: list index out of range

How would I go about getting it to catch the error?

Thanks in advance

You could check if the list has enough items before you are trying to get the value.

Otherwise, you could write a try/catch block around the list where you are working with the index and catch for IndexError. But i wouldnt recommend this solution if you can check yourself the index.

Edit: For more help, i would post the script or the lines where the error appears. In your case it should be at line 81

You trying to catch an Index Error while taking in the input, but, you should try catching the index error where it is actually happening, eg, in the error description that you provided:

File "*****", line 
81, in mark_visited
 if data[mark_visited][3] == "v":
IndexError: list index out of range

Thus, you should expect the error in line 81. But, if you can check that the index is acceptable before actually trying to access the value by index, you should probably do it, for instance, like this:

while True:
    try:
        mark_visited = int(input("Enter the number of a place to mark as visited \n>>> ")) - 1
        break
    except ValueError:
        print("Invalid input, enter a valid number")
    if mark_visited > len(data)-1:
        # Handle the case of the index that is out of range

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