python - Recursion in function causing return variable to equal 'None' -


this question has answer here:

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

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -