Friday, November 13, 2009

???

I wrote this for the num_even_digits function
        count = 0
        while n:
            n = n/10
            if n % 2 == 0:
                count = count + 1
        return count


but whenever I doctest it, it says
File "ch06draft.py", line 7, in __main__.num_even_digits
Failed example:
    num_even_digits(1357)
Expected:
    0
Got:
    1






why?

1 comment:

  1. Ahh, such fun! Think about your loop. When does it end? When n == 0. How does n get to be 0? It gets to be 0 by first becoming a number smaller than 10, so that n/10 is 0. Since you count this after it happens (0 % 2 == 0 is True), you will always get a least 1.

    Simple fix: reverse the order of two of your statements.

    ReplyDelete