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

67 Views Asked by At

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`
2

There are 2 best solutions below

0
Ajeet Verma On BEST ANSWER

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)
0
OM222O On

you're missing password = generate_password(length)

Also a set would be a much better data structure (pass_set instead of pass_list) for your operations.

import random
import string

def generate_password(length):
    alpha = list(string.ascii_letters + string.digits)
    return ''.join(random.sample(alpha, length))
        

def generate_passwords(count, length):
    pass_set = set()
    while(len(pass_set) < count):
        pass_set.add(generate_password(length))
    print(pass_set)        

generate_passwords(5, 10)