Python添加异常(已编辑)

2024-10-16 20:48:58 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个学习python的简单程序,因为我是初学者。如果用户输入了y,y,n,n以外的内容,我该如何添加一个异常呢?我搜索了所有地方,但似乎找不到要使用的异常?谢谢大家的帮助。在

在编辑:我调整了我的密码。唯一不起作用的是 如果(欢迎字符串.strip()。降低()!=“n”或“y”): welcomeString=input('不是有效的选择\n是否要反转字符串?(y/n):')。 它不实现用户输入y或n,但是它可以处理其他字母。在

EDIT2:在用户第二次输入无效输入之前,一切都按预期工作。第一次它会说“不是一个有效的选择”,但第二次,程序将退出。在

    import sys 

welcomeString = input('Welcome to String Reverser\nWould you like to reverse a string?(y/n)')

if not welcomeString.strip().lower() in ['n','y']:
  welcomeString = input('Not a valid choice\nWould you like to reverse a string?(y/n):')

if welcomeString.strip().lower() == 'n':
    print("Thanks for using String Reverser")

while welcomeString.strip().lower() == 'y': 
    myString = input("What string would you like to reverse?:")
    ReverseString = myString[::-1]
    print (("Your Reversed String is %s") % ReverseString)
    welcomeString = input("Would you like to reverse another string(y/n)")

Tags: to字符串用户程序youinputstringlower
3条回答

无效的用户输入通常不应导致引发异常。例外情况适用于特殊情况。这不是一个硬性的规则,你可以说一些标准的异常没有遵循它,但是处理这种用户输入验证的方法是常规的流控制。使用if语句检查它是否有效,如果无效,请再次询问他们或采取其他合理的措施。在

关于您的编辑,这就是您的代码无法工作的原因:

if(welcomeString.strip().lower() != 'n' or 'y'):

{cd2>使用这个方法是不对的。其评估结果为:

if(welcomeString.strip().lower() != ('n' or 'y')):

其结果是:

if(welcomeString.strip().lower() != 'n'):

这不是你想要的。改用这个:

if not welcomeString.strip().lower() in ['n', 'y']:

在这种情况下,您实际上并不需要异常-异常往往是阻止程序继续的异常情况,如果它仍然可以继续,但在某些情况下,由于用户输入或条件的原因,它可能会使用警告来表示。在

在这里,您可以使用任意数量的方法轻松地检查输入,并重复操作,直到您能够获得有效的输入:)。在

如果您决定使用异常:

您可以查看here以了解有关如何使用异常的更多详细信息,here可以查看如何将异常子类化并生成用户定义的异常

所以你可以做三件事:

1)有一个断言-这将导致一个断言错误,你的文本作为语句被视为错误

a = 1
b = 2 
assert a==b, "A does not Equal B"

assert通常用于检查边界-例如assert index>;=0,并且往往缺少临界值,但如果是您自己的个人代码,则可以使用它们进行测试。在

对于您的案例,您可以像当前一样拥有switch语句/if-else链。因此,正如@Ketouem上面所说,你可以有一个所有字母的列表和check或dict(如果你有更多的字母,比如100,这会稍微快一点)。在

Python wiki给出了正确使用断言的一般准则:

Places to consider putting assertions:

  • checking parameter types, classes, or values
  • checking data structure invariants
  • checking "can't happen" situations (duplicates in a list, contradictory state variables.)
  • after calling a function, to make sure that its return is reasonable

    -- Python Wiki

2)您可以使用一个内置的异常(lookhere)和raise其中一个;例如

^{pr2}$

不过,它们通常都会考虑specific uses。在

3)您可以像Numpy和许多库一样创建自己的异常(您也可以使用一个库,比如Numpy的LinAlgError,但除非您手动捕获和重新抛出,否则这些异常通常具有特定于域的用途。在

要创建自己的异常,您应该将exception的子类而不是BaseException

例如

class MyInputError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

以后再叫这个

if(condition_not_met):
    raise MyInputError("Wrong input. Please try again")

最后,您可以始终使用if-then's和其他控制结构,然后退出-但这在Python中并不常见,在C等语言中更常见

一般来说,尝试某些东西并捕捉错误是Python中更关键的范例之一:

EAFP Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

--Python Glossary

相关问题 更多 >