异常处理程序检查变量的内联脚本是否有效 [英] Exception handler to check if inline script for variable worked

查看:206
本文介绍了异常处理程序检查变量的内联脚本是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要添加异常处理,考虑第7行是否失败,因为查询和数组品牌之间没有交集。我是新来使用异常处理程序,不胜感激任何建议或解决方案。

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 brand
    except 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 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)

您的函数现在递归,因为它包含对其自身的调用。会发生什么情况,如果尝试抛出错误,之外的将被触发,提示用户重新定义查询。该功能然后是reran。

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.

如果没有错误被 intersection() code>而是返回一个空容器,您可以执行以下操作:

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 brand

brands = ["apple", "android", "windows"]
brand = None
while not brand:
    query = input("Enter your query: ").lower()
    brand = brandSelector(query)
print(brand)

其中看起来很像 Tuan333的答案。

这篇关于异常处理程序检查变量的内联脚本是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆