当用户输入的参数多于函数可以处理的参数时如何获取与 TypeError 相关的异常

How to get exception related to TypeError when user input more arguments than the function can handle

我正在尝试在我的代码中实现一个 try/exception,我希望当用户输入的参数多于函数预期的参数时异常打印“错误”。

问题是我下面的代码不打印“错误”信息,而是打印标准信息:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: text_analyzer() takes from 0 to 1 positional arguments but 2 were given

因为它是一个 TypeError,我在我的异常中使用了这个选项,但仍然不起作用。

这是代码

import string


def text_analyzer(text=None):
    try:
        ucase = 0
        lcase = 0
        punc = 0
        space = 0
        while not text:
            text = input("What is the text to analyze?")
        for letter in text:
            if letter in string.ascii_uppercase:
                ucase += 1
            elif letter in string.ascii_lowercase:
                lcase += 1
            elif letter in string.punctuation:
                punc += 1
            elif letter in string.whitespace:
                space += 1
        size = len(text)
        print(
            f"The text contains {size} characteres:\n"
            f"- {ucase} upper letters\n"
            f"- {lcase} lower letters\n"
            f"- {punc} punctuation marks\n"
            f"- {space} spaces\n"
        )
    except TypeError:
        print("Error")
    except Exception:
        print("Error")

我发现我应该在函数外使用 try/exception 才能工作。

我发现一个更好的解决方案是使用 *args。它对我有用。

这是固定的代码:

import string


def text_analyzer(text=None, *args):
    ucase = 0
    lcase = 0
    punc = 0
    space = 0

    if len(args) > 0:
        print("Error")
        return
    while not text:
        text = input("What is the text to analyze?")
    for letter in text:
        if letter in string.ascii_uppercase:
            ucase += 1
        elif letter in string.ascii_lowercase:
            lcase += 1
        elif letter in string.punctuation:
            punc += 1
        elif letter in string.whitespace:
            space += 1
    size = len(text)
    print(
        f"The text contains {size} characteres:\n"
        f"- {ucase} upper letters\n"
        f"- {lcase} lower letters\n"
        f"- {punc} punctuation marks\n"
        f"- {space} spaces\n"
    )