参数在 python 中的函数

function with arguments in python

我正在学习如何使用 python 编程。 我写了这个小程序来计算字符串中字符的数量。 实际上我的函数不接受参数并等待用户这样做。 我希望我的函数采用 2 个参数。一个用于字符串,另一个用于要搜索的字符。 这是我的脚本:

def count():
#word = 'banana'
 count = 0
 word = raw_input ('Enter a string:')
 letter = raw_input ('Enter a character:')
 for letter in word:
  if letter == 'a':
   count = count + 1
 print count

print count()

我想像这样运行我的函数:

>> count('banana', 'a')
3
def count(word, searched):
    count = 0
    for letter in word:
        if letter == searched:
            count = count + 1
    return count


word = raw_input('Enter a string:')
letter = raw_input('Enter a character:')
print count(word, letter)
def count(word, letter):
  count = 0
  for l in word:
    if l == letter:
      count = count + 1
  return count

word = raw_input('Enter a string:')
letter = raw_input('Enter a character:')
print count(word, letter)   

可以使用字符串的计数方法

def count(word, character):
    count = word.count(character)
    return count

word = raw_input ('Enter a string:')
letter = raw_input ('Enter a character:')

print count(word, letter)