Skip to content

Instantly share code, notes, and snippets.

Created December 31, 2015 16:35
Show Gist options
  • Save anonymous/4a752288b785312ca840 to your computer and use it in GitHub Desktop.
Save anonymous/4a752288b785312ca840 to your computer and use it in GitHub Desktop.
import string
import random
def pw_gen(size = 8, chars=string.ascii_letters + string.digits + string.punctuation):
return ''.join(random.choice(chars) for _ in range(size))
print(pw_gen(int(input('How many characters in your password?'))))
@master-stm
Copy link

hi, can i get some explanation for the function above ?

@iojeda
Copy link

iojeda commented Jun 11, 2020

hi, can i get some explanation for the function above ?

Hi, I suppose is a little bit late for the answer but It might help others.

This function returns a string (by default of 8 characters) by randomly picking characters from any alphabetic character (lowercase or uppercase) digits and punctuation characters

The function takes 2 arguments

def pw_gen(size, chars)

The first argument size gets initialized by default to 8, that means if you don't pass a size on the function call it will take 8
Second argument is a string initialized by default with the ascii letters (from a-Z) digits (0-9) and punctuation characters
This string is used as source of the character map used for your generated password

The body of the function contains a return method that does the following

  • converts a list into a string by using the ''.join()

  • random.choice(chars) function returns a random char from the previously generated chars string

  • for _ in range(size) is a loop that gets executed size times

So basically random.choice(chars) for _ in range(size) gives a list of size elements which are characters picked randomly from chars
and then that gets converted into a string by using ''.join()

In order to get a better understanding on few concepts used in this code I will provide some links

Role of underscore in Python - https://www.datacamp.com/community/tutorials/role-underscore-python
Random module - https://docs.python.org/3.8/library/random.html?highlight=random#module-random
String module - https://docs.python.org/3.8/library/string.html?highlight=string#module-string

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment