Mike Varela
Mike Varela

Reputation: 527

Need help with basic function - Python

want to count the number of times a letter appears in a string, having issues here. any help

def countLetters(string, character):
    count = 0
    for character in string:
        if character == character:
            count = count + 1
    print count

Upvotes: 0

Views: 267

Answers (3)

Dominic Bou-Samra
Dominic Bou-Samra

Reputation: 15406

The others have covered the errors of your function. Here's an alternative way of doing what you want. Python's built-in string method count() returns the number of occurrences of a string.

x = "Don't reinvent the wheel."
x.count("e")

Gives:

5

Upvotes: 10

Brendan Long
Brendan Long

Reputation: 54242

if character == character:

character will always equal character because they're the same variable. Just change the names of those variables. Maybe search_character?

I also wouldn't use string as a variable name since it's the name of a built-in module.

Upvotes: 3

NullUserException
NullUserException

Reputation: 85458

You have the same variable name for those characters (which means they'll always be equal). Try:

def countLetters(string, character):
    count = 0
    for char in string:
        if char == character:
            count = count + 1
    print count

Of course this is the same as str.count()

Upvotes: 1

Related Questions