Python 当用户输入的参数超过函数所能处理的数量时,如何获取与TypeError相关的异常
我试图在代码中实现一个try/exception,当用户输入的参数超过函数预期时,我希望该异常打印“Error” 问题是,我下面的代码没有打印“错误”消息,但它打印的是标准消息:Python 当用户输入的参数超过函数所能处理的数量时,如何获取与TypeError相关的异常,python,python-3.x,try-except,Python,Python 3.x,Try Except,我试图在代码中实现一个try/exception,当用户输入的参数超过函数预期时,我希望该异常打印“Error” 问题是,我下面的代码没有打印“错误”消息,但它打印的是标准消息: Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: text_analyzer() takes from 0 to 1 positional arguments
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
我发现我应该在函数之外使用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"
)
您尚未显示如何调用
text\u analyzer
;这种错误发生在您进入函数之前。(参数数量错误不是类型错误。)
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"
)