Python,计算偶数位数

2024-04-20 06:48:39 发布

您现在位置:Python中文网/ 问答频道 /正文

对于python入门课上的作业,其中一个问题是计算n中的偶数个数。到目前为止,我的代码如下:

def num_even_digits(n):
    i=0
    count = 0
    while i < n:
        i+=1
        if n%2==0:
            count += 1
    return count

print(num_even_digits(123456))

Tags: 代码returnifdefcount作业numeven
2条回答

你每次都在比较整数。您需要将它转换为一个字符串,然后循环该数字字符串中的每个数字,将其转换回整数,并查看其余数是否为0

def num_even_digits(numbers):
    count = 0
    numbers = str(numbers)
    for number in numbers:
        try:
            number = int(number)
        except ValueError:
            continue

        if number % 2 == 0:
            count += 1
    return count

print(num_even_digits(123456))

如果您想实际循环使用0到大数值范围内的每个可能的数字,您可以这样做。在

^{pr2}$

当前功能的问题:

def num_even_digits(n): # n is not descriptive, try to make your variable names understandable
    i=0
    count = 0
    while i < n: # looping over every number from 0 to one hundred twenty three thousand four hundred and fifty six.
        i+=1
        if n%2==0: # n hasn't changed so this is always going to be true
            count += 1
    return count

print(num_even_digits(123456))

Python的回答:

def num_even_digits(x):
    return len([ y for y in str(x) if int(y) % 2 == 0])

print(num_even_digits(123456))

免责声明:我认识到,对于一个介绍性的Python类,我的回答可能不合适。在

相关问题 更多 >