温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - programing function in python
count function python

其他 - python中的编程功能

发布于 2020-04-04 10:23:28

我正在尝试创建一个带有两个参数的函数:D =数字(0-9)和n =正数。

如果D是奇偶数,函数应该给我0,但是,如果D是奇数,函数应该计算我在n中具有的奇数。

这段代码有问题,但是我不知道是什么:

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

查看更多

提问者
AUinIS
被浏览
102
phoenixo 2020-01-31 21:42

我改变了两件事:

  • while n > 1:而不是while n > 0:否则,您的循环永不停止
  • n=n//10而不是n=n/10//欧几里得分割在哪里,这是您需要的

您应该尝试这样:

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)