代码抛出错误:只能将str(而不是“NoneType”)连接到str

2024-09-26 18:10:17 发布

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

S为空时,它似乎正在运行,但由于我的第一个if语句,它不应该运行

它在第15行抛出错误:只能将str(而不是“NoneType”)连接到str

def encipher(S, n):
    """
    Returns a forward shifted string based on the rules of caesar cipher
    Argument S: String to be shifted
    Argument n: number of spaces shifted
    """

    if len(S) > 0:  
        if ord("a")<=ord(S[0])<=ord("z"):   #lowercase letters
            if ord("a") <= ord(S[0])+n <= ord("z"):   #if the shifter letter is in the alphabet range add
                return rot(S[0],n) + encipher(S[1:],n)
            else:                                   #else subtract
                return rot(S[0],(n-26)) + encipher(S[1:],n)
        elif ord("A")<=ord(S[0])<=ord("Z"):   #uppercase letters
            if ord("A") <= ord(S[0])+n <= ord("Z"): #if the shifter letter is in the alphabet range add
                return rot(S[0],(n)) + encipher(S[1:],n)
            else:                               #else subtract
                return rot(S[0],(n-26)) + encipher(S[1:],n) 
        else:
            return S[0] + encipher(S[1:],n)
    else:
        return 
        
def rot(c, n):
    #shifts a character
    if len(c)>0:
        return chr(ord(c)+n)
    else: 
        return 

Tags: ofthelenreturnifdefargumentelse
2条回答

encypher到达字符串的最后一个字符时,它将使用空字符串调用函数'

S = 'a'
S[1:]

输出:“”

它将根据您的代码返回None值。 请更改返回值:

return ''

您有None个返回,只要将它们更改为字符串("")就可以了

def encipher(S, n):
    """
    Returns a forward shifted string based on the rules of caesar cipher
    Argument S: String to be shifted
    Argument n: number of spaces shifted
    """

    if len(S) > 0:
        if ord("a") <= ord(S[0]) <= ord("z"):  # lowercase letters
            if ord("a") <= ord(S[0]) + n <= ord("z"):  # if the shifter letter is in the alphabet range add
                return rot(S[0], n) + encipher(S[1:], n)
            else:  # else subtract
                return rot(S[0], (n - 26)) + encipher(S[1:], n)
        elif ord("A") <= ord(S[0]) <= ord("Z"):  # uppercase letters
            if ord("A") <= ord(S[0]) + n <= ord("Z"):  # if the shifter letter is in the alphabet range add
                return rot(S[0], (n)) + encipher(S[1:], n)
            else:  # else subtract
                return rot(S[0], (n - 26)) + encipher(S[1:], n)
        else:
            return S[0] + encipher(S[1:], n)
    else:
        return ""


def rot(c, n):
    # shifts a character
    if len(c) > 0:
        return chr(ord(c) + n)
    else:
        return ""

S = "b"
n = 3
print(encipher(S, n))

输出:

e

相关问题 更多 >

    热门问题