[Tutor] need help with python for counter

Dave Angel d at davea.name
Wed Dec 19 11:12:18 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
>
> print count
>
>

Two separate problems in that code, either of which would be enough to
ruin the count value.

1) Your code sets the count to zero INSIDE the loop, so every time
through, you trash whatever earlier value you had.  This assures that
only the last loop matters!

You ought to be zeroing the counter just once, before the loop starts.

2) In your else clause, as soon as you encounter some other character,
the code is zeroing the counter.

count = 0

for i in number:
    if i == digit:
        count += 1

While I've got your attention, let me point out that nowhere in your
description do you actually tell us what values you're entering, and
what values you expect.  You ought to supply sample values which
illustrate the problem.  The above code is really only a guess, as to
what you wanted.

But the notion of doing the initialization OUTSIDE the loop is an
important one, and I'm sure that part is correct.

-- 

DaveA



More information about the Tutor mailing list