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
中,因为它应该是一个关闭的文件.我不在同一个文件中执行,所以异常应该独立于其他文件.
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...
感谢您的回答!禁止
推荐答案
当你使用 def 声明你想要一个名为
,像这样调用你的函数或者用你想要的任何字符串输入words
的参数时,你并没有将参数传递给你的函数(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屋!