I need to add exception handling that considers if line 7 fails because there is no intersection between the query and array brands. I'm new to using exception handlers and would appreciate any advice or solutions.
I have written an example structure for exception handling, but I am not certain whether it will work.
brands = ["apple", "android", "windows"]query = input("Enter your query: ").lower()
brand = brandSelector(query)
print(brand)def brandSelector(query):try: brand = set(brands).intersection(query.split())brand = ', '.join(brand)return brandexcept ValueError:print("Brand does not exist")# Redirect to main script to enter correct brand in query
This is not the best way to do it, but it is a way.
def brandSelector(query):try:brand = set(brands).intersection(query.split())brand = ', '.join(brand)return brandexcept ValueError:print("Brand does not exist")query = input("Enter your query: ").lower()brandSelector(query)brands = ["apple", "android", "windows"]
query = input("Enter your query: ").lower()
brand = brandSelector(query)
print(brand)
Your function is now recursive since it includes a call to itself. What happens is that if the try
throws an error, the except
gets triggered where the user is prompted to redefine the query. The function is then reran.
If no error is thrown by the intersection()
but instead an empty container is returned, you can do the following:
def brandSelector(query):brand = set(brands).intersection(query.split())brand = ', '.join(brand)return brandbrands = ["apple", "android", "windows"]
brand = None
while not brand:query = input("Enter your query: ").lower()brand = brandSelector(query)
print(brand)
Which looks a lot like Tuan333's answer.