Is the Nesting Pythonic feature?

I am learning Python on my R.Pi and I hit a little snag. It seems to me that the following code will leave the "inputchecker" function open in memory until it returns to the "getinput" function.

Is this bad code? Should it be done differently?

def getinput(i):    
    if i == 1:
        first = input("Would you like A or B? ")
        inputchecker(1, first)
    elif i == 2:
        second = input("Would you like C or D? ")
        inputchecker(2, second)

def inputchecker(n, userinput):    
    def _tryagain_(n):
        usage(n)
        getinput(n)        
    if n == 1:
        if userinput in ("A", "B"):
            print("You chose wisely.")
            getinput(2)
        else:
            _tryagain_(n)
    elif n == 2:
        if userinput in ("C", "D"):
            print("You chose wisely.")
        else:
            _tryagain_(n)

def usage(u):
    if u == 1:
        print("Usage: Just A or B please.") 
    if u == 2:
        print("Usage: Just C or D please.") 


getinput(1)
+4
source share
4 answers

No, the name getinputin the nested function does not create the link. It is scanned every time it is called _tryagain_because it is global. Not that this is important, since the module is cleared as a whole when Python exits, there is no real possibility of a memory leak.

, , . , . , .

+2

, , . , while

def getinput(i):
    while i:    
        if i == 1:
            first = input("Would you like A or B? ")
            i = inputchecker(1, first)
        elif i == 2:
            second = input("Would you like C or D? ")
            i = inputchecker(2, second)

def inputchecker(n, userinput):          
    if n == 1:
        if userinput in ("A", "B"):
            print("You chose wisely.")
            return 2
        else:
            getusage(i)
            return i
    elif n == 2:
        if userinput in ("C", "D"):
            print("You chose wisely.")
        else:
            getusage(i)
            return i

, , . , .

+1

, , . , make, validation boolean . , , , .

- - : :

def getinput():
    valid = False
    while not valid:
        first = input("Would you like A or B? ")
        valid = inputIsValid(1, first)
    valid = False
    while not valid:
        second = input("Would you like C or D? ")
        valid = inputIsValid(2, second)
    return [first, second]

def inputIsValid(n, userinput):    
    valid = False
    if n == 1:
        valid = userinput in ("A", "B")
    elif n == 2:
        valid = userinput in ("C", "D")
    if valid:
        print("You chose wisely.")
    else:
        usage(n)
    return valid

def usage(u):
    if u == 1:
        print("Usage: Just A or B please.") 
    elif u == 2:
        print("Usage: Just C or D please.") 

getinput() 
0

"pythonic": python , . , . , slow.

, , "pythonic"

-1

Source: https://habr.com/ru/post/1661619/


All Articles