Python 3异常:TypeError:函数缺少1个必需的位置参数:'words' [英] Python 3 Exception: TypeError: function missing 1 required positional argument: 'words'
问题描述
我的函数需要一个参数单词,但我希望程序在没有参数的情况下也不会崩溃。
My function needs one argument words, but i want the program not to crash if no argument.
def get_count(words):
try:
consonants_str = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
vowels_str = "aeiouAEIOU"
consonants_ls = []
vowels_ls = []
words_ls = []
result = {"vowels": 0, "consonants": 0}`
for element in consonants_str:
consonants_ls.append(element)
for element in vowels_str:
vowels_ls.append(element)
if type(words) != type(None):
for element in words:
words_ls.append(element)
for element in words_ls:
if element in vowels_ls:
result["vowels"] += 1
if element in consonants_ls:
result["consonants"] += 1
else:
continue
else:
result["vowels"] = 0
result["consonants"] = 0
except TypeError:
result["vowels"] = 0
result["consonants"] = 0
answer = {"vowels": result["vowels"],"consonants": result["consonants"]}
return answer`
因此,如果我使用
print(get_count())
我想要的是,该程序不会向我显示类似于标题中的错误。例外应该在 get_count
的 def
中,因为它应该是封闭文件。我不在同一个文件中执行,因此Exception应该独立于其他文件。
I want, that the program doesn't show me an error like the one in the heading. The exception for that should be in the def
of get_count
because it should be a closed file. I don't execute in the same file, so the Exception should be independent from other files.
希望您能理解我的意思...
I hope you understand what I mean...
感谢您的回答!
NoAbL
Thanks for your answers! NoAbL
推荐答案
当您声明要使用名为 words
和 def(words)
,像这样或您需要的任何字符串输入调用函数
You're not passing an argument to your function, when you declared that you want an argument named words
with def(words)
, call your function like this or with any string input you desire
print(get_count('AAAABBBKDKDKDKDA'))
如果您希望在不传递任何参数时退出程序,请执行此操作(记住单词现在是一个元组)
if you want the program to exit when no argument is passed, do this (remember words is now a tuple)
import sys
def get_count(*words):
if not words: # if words is empty, no argument was passed
sys.exit('You passed in no arguments')
else:
pass # do something with the items in words
这篇关于Python 3异常:TypeError:函数缺少1个必需的位置参数:'words'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!