python - Recursion in function causing return variable to equal 'None' -
this question has answer here:
- recursive function returning none? 1 answer
i making caesar cipher in python. had created function return message user want encrypt. wanted same cipher key. wanted function return key if between 1 , 26 because size of alphabet. works when purposefully enter number bigger 26 enter number in between 1 , 26; apparently returns 'none'. first time using recursion.
def getkey(): print("enter key want use decrypt/encrypt message") key = int(input()) # key input while true: if key >= 1 , key <= 26: #checking if key in between range return key #giving key else: # should run whenever input invalid print ("the key must inbetween 1 , 26") break # stop loop getkey() # recursion, restart function key = getkey() print(key) # prints 'none'
what happened key? did go!?
your code rewritten as:
def getkey(): print("enter key want use decrypt/encrypt message") key = int(input()) # key input while true: if key >= 1 , key <= 26: #checking if key in between range return key #giving key else: # should run whenever input invalid print ("the key must inbetween 1 , 26") break # stop loop getkey() # recursion, restart function throw away result return none # falling off end of function does. key = getkey() print(key) # prints 'none'
the solution is:
def getkey(): print("enter key want use decrypt/encrypt message") key = int(input()) # key input if key >= 1 , key <= 26: #checking if key in between range return key #giving key else: # should run whenever input invalid print ("the key must inbetween 1 , 26") return getkey() # recursion, restart function
note have removed loop, because if recursing, ever go round loop once. better solution retain loop , not use recursion:
def getkey(): print("enter key want use decrypt/encrypt message") while true: key = int(input()) # key input if key >= 1 , key <= 26: #checking if key in between range return key #giving key else: # should run whenever input invalid print ("the key must inbetween 1 , 26") # don't stop loop. try again.
Comments
Post a Comment