我需要添加考虑第7行是否失败的异常处理,因为查询和数组品牌之间没有交集。我是使用异常处理程序的新手,不胜感激任何建议或解决方案。
我已经为异常处理编写了一个示例结构,但是不确定它是否会起作用。
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 brand
except ValueError:
print("Brand does not exist")
# Redirect to main script to enter correct brand in query
最佳答案
这不是最佳方法,但是是。def brandSelector(query):
try:
brand = set(brands).intersection(query.split())
brand = ', '.join(brand)
return brand
except 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)
您的函数现在是递归的,因为它包括对自身的调用。发生的情况是,如果try
引发错误,则会在提示用户重新定义查询的地方触发except
。然后重新运行该功能。
如果intersection()
没有引发任何错误,而是返回了一个空容器,则可以执行以下操作:def brandSelector(query):
brand = set(brands).intersection(query.split())
brand = ', '.join(brand)
return brand
brands = ["apple", "android", "windows"]
brand = None
while not brand:
query = input("Enter your query: ").lower()
brand = brandSelector(query)
print(brand)
看起来很像 Tuan333的答案。