我刚刚学习 python,我遇到了一个问题,要求我将一个字符串作为我的“计数字母函数”的输入。
该函数应该计算给定单词(具体来说,用户输入的水果)中有多少个“a”。
最终值是正确的,但在我的函数中,如果您愿意,它会列出程序“过程”,方法是列出每个索引处有多少个 “a” 并添加之前的所有内容.
我只想要一个最终值,而不是列表。
如果我不太清楚,这是我的程序,你自己测试一下看看我的意思,也许能帮助我找到解决方案?
def count_letters(a):
count=0
for char in a:
if char == 'a':
count+=1
print count
a=raw_input("Name a fruit and I will tell you how many letters are in it." + '\n')
print count_letters(a)
请您参考如下方法:
只是改变:
for char in a:
if char == 'a':
count+=1
print count
收件人:
for char in a:
if char == 'a':
count+=1
print count
否则每次 for 循环运行时你都会打印计数器。
此外,您在 print count_letters(a) 处使用 print 调用您的函数。
您不需要这个,因为您已经在代码的最后一行放置了打印语句。如果您将 print 语句留在那里以调用您的函数,它将打印 None,因为该函数已经返回了计数值。
所以你也可以改变:
print count_letters(a)
收件人:
count_letters(a)
print count_letters(a) 的输出示例:
Name a fruit and I will tell you how many letters are in it. abacaxi
3
None
count_letters(a) 的输出示例:
Name a fruit and I will tell you how many letters are in it. abacaxi
3
