[Tutor] need help with python for counter
Mitya Sirenef
msirenef at lightbird.net
Wed Dec 19 07:12:32 CET 2012
On 12/19/2012 12:40 AM, Brandon Merritt wrote:
> I feel silly, but I'm having the darndest time trying to figure out
> why this for counter won't work. I know that there is the count method
> for the string class, but I was just trying to do it the syntactical
> way to prove myself that I know the very basics. As of right now, my
> script is just returning 1 or 0, even if I very clearly make sure that
> I specify at least 4 instances of the digit in my number string:
>
> number = raw_input('Enter a 7-unit number: ')
>
> digit = raw_input('Enter a single digit: ')
>
> for i in number:
> count = 0
> if i == digit:
> count += 1
> else:
> count = 0
Why do you have the else: clause?
You can also do:
count = sum(i==digit for i in number)
I think this is very clear and short..
-m
--
Lark's Tongue Guide to Python: http://lightbird.net/larks/
More information about the Tutor
mailing list