Search code examples
pythonfunctionnested-function

Why won't calling a nested function result in returning original function's value?


Somehow I can't manage to use a previously defined function inside another one. Is that possible?

def generate_password(length):
    import random
    password = str()
    alpha_num = [i for i in 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789']
    while len(password) <= length:
        symbol = random.choice(alpha_num)
        if symbol not in password:
            password += symbol
        else: 
            symbol = random.choice(alpha_num)
    return(password)
        

def generate_passwords(count, length):
    import random
    passlist = []
    for j in range(count):
        generate_password(length)
        if password not in passlist:
            passlist.append(password)
    print(passlist)        

n, m = int(input()), int(input())
generate_passwords(n, m)

this code returns an error:

 
`Traceback (most recent call last):
  File "jailed_code", line 24, in <module>
    generate_passwords(n, m)
  File "jailed_code", line 19, in generate_passwords
    if password not in passlist:
NameError: name 'password' is not defined`

Solution

  • You need to assign the returned value from the function call generate_password(length) into a variable (here, password) to be able to use it further.

    def generate_password(length):
        import random
        password = str()
        alpha_num = [i for i in 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789']
        while len(password) <= length:
            symbol = random.choice(alpha_num)
            if symbol not in password:
                password += symbol
            else: 
                symbol = random.choice(alpha_num)
        return(password)
            
    
    def generate_passwords(count, length):
        import random
        passlist = []
        for j in range(count):
            password = generate_password(length)
            if password not in passlist:
                passlist.append(password)
        print(passlist)        
    
    n, m = int(input()), int(input())
    generate_passwords(n, m)