Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The module function returns one character instead of the specified number

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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And: random_index = generator.secret_question_generator()

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading