Recursion in function causing return variable to equal 'None'

Question:

I am making a Caesar cipher in Python. I had created a function to return the message the user would want to encrypt. I then wanted to do the same for cipher key. I wanted the function to only return the key if it was between 1 and 26 because that is the size of the alphabet. It works but when I purposefully enter a number bigger than 26 THEN enter a number that is in between 1 and 26; it apparently returns ‘None’. This is my first time using recursion.

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' 

What happened to the key? Where did it go!?

Asked By: user3124306

||

Answers:

Your code could be rewritten as:

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' 

The solution is:

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

Note that I have also removed the loop, because if you are recursing, you only ever go round the loop once. A better solution is to retain the loop and not use recursion:

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.