3

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?

2
  • i would use this instead "banana".count("a") Commented Sep 28, 2013 at 20:55
  • Foo Bar, I agree, but the Python book's exercise states: Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments. Defining a new count function with those two arguments. pythonlearn.com/html-270/book007.html#hevea_default363 Commented May 27, 2016 at 17:58

4 Answers 4

9

a and banana are variable names. Since you never defined either of them (e.g. a = 'x'), the interpreter cannot use them.

You need to wrap them in quotes and turn them into strings:

count_letters('a', 'banana')

Or assign them beforehand and pass the variables:

l = 'a'
s = 'banana'

count_letters(l, s)
Sign up to request clarification or add additional context in comments.

Comments

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')

Comments

0

this is with 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)

Comments

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

1 Comment

Welcome to Stack Overflow! While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.