DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Hamza Hesham
Hamza Hesham

Posted on

Password generator using python

Hello, today we will make a simple password generator program using python.
first, we will import random and make 2 new variables:

import random 
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-+=!@#$%^&*"
length_of_pass = int(input("num of letters:"))

Second, we will define a function that has one parameter called "num",
Inside the function we will make a new empty variable called password , After that we will loop in the range of "num" using "for loop", Inside the loop we will we will use the random module and add the result to password, outside the for loop we will return password:

def pass_generator(num):
    password = ''
    for i in range(num):
        password += random.choice(chars)
    return password

The last thing we will call the function with the parameter "length_of_pass".
the whole code:

import random 
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-+=!@#$%^&*"
length_of_pass = int(input("num of letters:"))
def pass_generator(num):
    password = ''
    for i in range(num):
        password += random.choice(chars)
    return password
print(pass_generator(length_of_pass))

Don't forget to follow me!
Thanks for reading.

Top comments (4)

Collapse
 
agtoever profile image
agtoever

Nice post. Two suggestions:

Use string constants to define possible characters:

import string
chars = string.letter + string.digits + string.punctuation

Often β€œsimple for loops” can be prevented in Python. In this case, you can do:

return β€œβ€.join(random.choices(chars, k=num))

Or if you insist on using choice:
return β€œβ€.join(random.choice(chars) for _ in range(num))

Collapse
 
thebadcoder profile image
TheBadCoder

I appreciate your work, you gave a good idea.I was thinking about this lately.. I will make use of this logic.
However i see a problem that at some cases the password might not have numbers or special characters for smaller lengths.. and for strong password those are specifically recommended.

Collapse
 
oxy_oxide profile image
Hamza Hesham Author • Edited on

OK I Agree but who will use password generator for a small password , And all the passwords these days must have numbers and special characters .

Collapse
 
oxy_oxide profile image
Hamza Hesham Author

Thanks!

🌚 Life is too short to browse without dark mode