2

I am completing a beginner's Python book. I think I understand what the question is asking.

Encapsulate into a function, and generalize it so that it accepts the string and the letter as arguments.

fruit = "banana"
count = 0
for char in fruit:
    if char == 'a':
        count += 1
print count

My answer is:

def count_letters(letter, strng):
    fruit = strng
    count = 0
    for char in fruit:
        if char == letter:
            count += 1
    print count

count_letters(a, banana)

But it is wrong: name 'a' is not defined. I don't know where I'm going wrong. I thought the interpreter should know that 'a' is the argument for 'letter', and so on.

So I must be missing something fundamental.

Can you help?

4

3 回答 3

9

a并且banana是变量名。由于您从未定义过它们中的任何一个(例如a = 'x'),因此解释器无法使用它们。

您需要将它们括在引号中并将它们转换为字符串:

count_letters('a', 'banana')

或者预先分配它们并传递变量:

l = 'a'
s = 'banana'

count_letters(l, s)
于 2013-09-28T20:47:20.287 回答
0
#!/usr/bin/python2.7

word = 'banana'

def count(word, target) :
    counter = 0
    for letter in word :
        if letter == target :
            counter += 1
    print 'Letter', letter, 'occurs', counter, 'times.'

count(word, 'a')
于 2016-05-27T16:08:25.210 回答
0

这是 Python 3:

def count_letters(letter, strng):
count = 0
for char in letter:
    if char == strng:
        count += 1
print(count)
a = input("Enter the word: ")
b = input("Enter the letter: ")
count_letters(a, b)
于 2020-04-15T14:07:31.200 回答