Warm tip: This article is reproduced from stackoverflow.com, please click
count function python

programing function in python

发布于 2020-04-04 10:10:13

I'm trying to create a function that take two parameters: D = digit (0-9) and n = positive number.

If the D is parity number, the function should give me 0 but ,if the D is odd number, the function should count numbers of odd number I have in n.

There is a problem with this code but I don't know what:

def testD(D,n):
    if D % 2 == 0:
        return 0
    count = 0
    while n > 0:
        if(n%10) %2==1:
            count +=1
        n=n/10
    return count
Questioner
AUinIS
Viewed
62
phoenixo 2020-01-31 21:42

I changed 2 things :

  • while n > 1: instead of while n > 0: otherwise your loop never stops
  • n=n//10 instead of n=n/10, where // is the euclidian division, which is what you need here

You should try this :

def testD(D,n):
    if D % 2 == 0:
        return 0
    count = 0
    while n > 1:
        if(n%10) %2==1:
            count +=1
        n=n//10
    return count

print(testD(7, 555))
# output : 3 (because 7 is odd, and there is 3 odd digits in 555)