Home > OS >  Catch wrong input within dict?
Catch wrong input within dict?

Time:04-13

I'm trying to display the error message "This doesn't work" when a user enters an input that does not match a key in the dict. Currently, when they enter a correct input (ie, "Audi" or "Ferrari", It'll display the "This works, Audi" but If incorrectly entered, nothing happens. Why? I could easily do it with if/elif but I want to tackle the error handling side. Thanks

while car_search !="Q" or car_search !="q":
    try:
        if car_search in car_dict.keys():
            car = car_dict[car_search]
            print("This works", car.make)
    except KeyError:
        print("This doesn't work")

CodePudding user response:

I corrected a bit your code and added comments

# if you want to capture both a lowercase and uppercase characters, 
# you can do something like:
# notice you might need a rstrip to eliminate newline characters
# in case your search_car comes from a console input
while car_search.lower().rstrip() != "q":
    # this is the EAFP approach. Try accessing the key, and handle 
    # the exception if the key does not exist
    try:
        car = car_dict[car_search]
        print("This works", car.make)
    except KeyError:
        print("This doesn't work")

    # here you have to request a new car_search,
    # otherwise you will run again and again the same option
    car_search = input("Input a car to search (q to exit)")

You can also use the LBYL approach, so you first check if the key exist before trying to access it.

while car_search.lower().rstrip() != "q":
    if car_search in car_dict.keys():
        print("This works", car.make)
    else
        print("This doesn't work")

    car_search = input("Input a car to search (q to exit)")
  • Related