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

How to run a function multiple times?

I’m trying to write a code that outputs a username and a password

import string, random

def random_string(length=9, uppercase=True, lowercase=True, numbers=True):
    character_set = ''

    if uppercase:
        character_set += string.ascii_uppercase
    if lowercase:
        character_set += string.ascii_lowercase
    if numbers:
        character_set += string.digits

    return ''.join(random.choice(character_set) for i in range(length))


username = random_string(9)

for num in range(30):
    password = f'{random.randint(100, 999)}{random.randint(100, 999)}{random.randint(100, 999)}'

print(f'{username}\n{password}')

This works on my end, but the problem I’m trying to solve is how do I let this run 30 times?

So I can get 30 different pairs of usernames and passwords.

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

>Solution :

If you want a collection of 30 random usernames and passwords, a list comprehension should serve nicely.

For instance:

[f'{random_string(9)}: {random.randint(100, 199)}' for _ in range(30)]

Obviously you can tweak this to generate the usernames and passwords howver you want, but it will give you a list of 30 of them that you can then use as you please.

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