Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generalize a function by adding arguments?

Tags:

python

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?

like image 629
BBedit Avatar asked Dec 29 '25 07:12

BBedit


1 Answers

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)
like image 171
Blender Avatar answered Dec 30 '25 23:12

Blender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!