将整数连接为字符串的 Nonetype 错误 Python

Nonetype error concatenating integers as strings Python

你好 Whosebugbros

我想出了一个有趣的问题来找出所有年份(在最近的未来,基本上是在我一天之前)以下所有情况都为真:

1) the day is prime (eg the 5th or the 17th of the month)
2) the month is prime (eg May is the 5th month 5 is prime)
3) the year is prime (eg the year 2027 is prime)
4) the numbers concatenated in DDMMYYYY format is prime (eg 3022027 is prime)

我的代码很好用。我得到以下答案:

3-02-2027    
13-02-2027
31-02-2027 ## February has 31 days now ok
31-05-2027
29-07-2027

但我也被告知 if isPrime(year) and isPrime(month) and isPrime(day) and isPrime(int(str(day) + datefix(month) + str(year))):

TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

我有两个问题:1) 我做错了什么? 2) 为什么我只在 2027 年得到答案(有点相关,如果有错误,为什么我根本没有得到任何答案)

def isPrime(n) :

    # Corner cases
    if (n <= 1) :
        return False
    if (n <= 3) :
        return True

    # This is checked so that we can skip
    # middle five numbers in below loop
    if (n % 2 == 0 or n % 3 == 0) :
        return False

    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6

    return True

def datefix(y):

    if y <= 9:
        y = str(str(0) + str(y))
        return y

print(type(datefix(5)))


years = range(2019, 2054) ## 2053 is a good year to stop - and it's prime
days = range(2, 32)
months = range(2,13)

for year in years:
    for month in months:
        for day in days:
            if isPrime(year) and isPrime(month) and isPrime(day) and isPrime(int(str(day) + datefix(month) + str(year))):
                print(str(day) + '-' + datefix(month) + '-' + str(year))

嗯,因为 datefix 只有 returns y 如果 y <= 9,那么如果不是,
它 returns None,Python.
中函数的默认 return 类型 因此,在您的示例中,月份大于 9。
函数 datefix 需要处理这种情况。

您实际上可以将您的函数 datefix 更改为单行 datefix = '{:02d}'.format 以获得零填充月份。无需考虑案例 greater/smaller 10. 目前它 returns None 用于参数> 9,如另一个答案中所述。