函数中的递归导致 return 变量等于 'None'

Recursion in function causing return variable to equal 'None'

我正在 Python 中制作凯撒密码。我为 return 用户想要加密的消息创建了一个函数。然后我想对密码密钥做同样的事情。如果键在 1 到 26 之间,我希望该函数仅 return 键,因为这是字母表的大小。它有效,但是当我有意输入一个大于 26 的数字时,然后输入一个介于 1 和 26 之间的数字;显然 returns 'None'。这是我第一次使用递归。

def getKey():
    print("Enter the key you want to use to decrypt/encrypt the message")
    key = int(input()) # key input
    while True:
        if key >= 1 and key <= 26: #checking if key is in between range
            return key #giving back the key
        else: # this should run whenever the input is invalid
            print ("The key must be inbetween 1 and 26")
            break # to stop the loop
    getKey() # Recursion, to restart the function

key = getKey()
print(key) # this prints 'None' 

钥匙怎么了?它去哪儿了!?

您的代码可以重写为:

def getKey():
    print("Enter the key you want to use to decrypt/encrypt the message")
    key = int(input()) # key input
    while True:
        if key >= 1 and key <= 26: #checking if key is in between range
            return key #giving back the key
        else: # this should run whenever the input is invalid
            print ("The key must be inbetween 1 and 26")
            break # to stop the loop
    getKey() # Recursion, to restart the function THEN THROW AWAY RESULT
    return None # This is what falling off the end of a function does.

key = getKey()
print(key) # this prints 'None' 

解决方法是:

def getKey():
    print("Enter the key you want to use to decrypt/encrypt the message")
    key = int(input()) # key input
    if key >= 1 and key <= 26: #checking if key is in between range
        return key #giving back the key
    else: # this should run whenever the input is invalid
        print ("The key must be inbetween 1 and 26")
        return getKey() # Recursion, to restart the function

请注意,我还删除了循环,因为如果你在递归,你只会绕过一次循环。更好的解决方案是保留循环而不使用递归:

def getKey():
    print("Enter the key you want to use to decrypt/encrypt the message")
    while True:
        key = int(input()) # key input
        if key >= 1 and key <= 26: #checking if key is in between range
            return key #giving back the key
        else: # this should run whenever the input is invalid
            print ("The key must be inbetween 1 and 26")
            # Don't stop the loop.  Just try again.