Hi folks,

Just hoping someone can show me where I'm going wrong here. I've been given a tutorial question to count the number of times a particular character (char) appears in a string. The only catch is that you need to use a for loop, as the online checker won't accept anything without a for loop somewhere.

So I set about using a for loop, but it didn't quite work out:

>>> def count(string, char):
	count = 0
	for c in string:
		if c == char:
			count = count + 1
		return count

	
>>> count('aaa','a')
1

I realise this is because more or less it's only being told to count the character in the string once then print. I had a poke around for a solution to this and along the way found the "real" (ie. Python count) way of doing it, and then scratched together what I thought would be a great way to go around the for loop requirement:

>>> def count(string, char):
	count = 0
	n = string.count(char)
	for c in string:
		if c == char:
			count = n
		return count

	
>>> count('a large carrot','a')
3
>>> count('"a large carrot"','a')
0
>>> count('a large carrot.','a')
3
>>> count('A large carrot.','a')
0
>>> count('Rabbits eat carrots.','a')
0
>>> count('raBbits eat carrots.','a')
0

As you can see, my problem now is that it works fine in cases where there are no "" or capital letters anywhere in the string. If either of those are introduced, it seizes up and returns zero.

If anyone can help me with either the "proper" (for loop) way of doing things, or my roundabout (mildly more successful but still not working) way of doing it, it would be greatly appreciated.

Cheers.

Recommended Answers

All 3 Replies

return count is indented too far.

Agh! How embarrassing! I ran it through IDLE too and it didn't pick it up; I suppose that's because it technically is valid.

Thanks for the reply. I've learnt a valuable lesson... be careful with the indenting, even if it seems to go through correctly.

Welcome to the wonderful world of Python programming. Just a note, avoid using function and module names for variable names. There are times when it will bite you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.