我在做一個編碼練習,其中一個測試調用下面定義的方法get_count()
。其中一個測試調用get_count()
而不傳遞任何參數。我希望函數仍然返回result = {'vowels':0, 'consonants':0}
,即使函數沒有任何參數被調用。有沒有辦法在Python中做到這一點?處理不帶參數調用函數的情況?
def get_count(words):
result = {'vowels':0, 'consonants':0}
if not words:
return result
if type(words) is not str:
return result
for letter in words.lower():
if letter in 'aeiou':
result['vowels'] += 1
elif letter.isalpha():
result['consonants'] += 1
return result
我最喜歡使用默認值時不想要的行爲的例子是這裏列出的第一個「面試問題」:https://www.toptal.com/python/interview-questions – jdogg