Home > Blockchain >  The module function returns one character instead of the specified number
The module function returns one character instead of the specified number

Time:07-23

I'm trying to divide a large code into modules.

Importing the created module. The module looks like this:

import random


def password_generator():
    big_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    small_alphabet = "abcdefghijklmnopqrstuvwxyz"
    digits = "0123456789"
    generator = big_alphabet   small_alphabet   digits
    random_password = ''
    for p in range(15):
        random_password  = random.choice(generator)
        return random_password


def secret_question_generator():
    digits = "0123456789"
    generator = digits
    random_index = ''
    for i in range(5):
        random_index  = random.choice(generator)
        return random_index

I call the function from the module as follows: random_password = generator.password_generator()

And: random_index = generator.secret_question_generator()

But the function returns one character at a time. How to fix the problem? Help please

CodePudding user response:

You put the return statement inside the for loop. Just unindent it so that the functions only return once the for loop is finished. In your code the loop only happens for i=0 and then it returns the one character that created.

for p in range(15):
    random_password  = random.choice(generator)
return random_password

CodePudding user response:

Lets look at a minimal example:

s = ""
for i in range(10):
  s  = "a"
  print(s)

And

s = ""
for i in range(10):
  s  = "a"
print(s)

What is the difference between the two? For the first one the print is part of every loop, so you print 10 times. For the second one it happens after the loop, so it only prints the full string.

But you call the return on the first iteration of the loop every time, which always instantly stops the function and returns a result.

The solution is to have

for i in range(14):
  # do your stuff
return (yourvalue)

So all 14 iterations run and then you return

CodePudding user response:

Return automatically ends function and in your case returns the string after first iteration. Simply erase indent before return statement:)

  • Related