1

i got a program from one of the site to make password generator.

import string
from random import *
characters = string.ascii_letters + string.punctuation  + string.digits
password =  "".join(choice(characters) for x in range(randint(8, 16)))
print password

can someone explain what would be stored in "password" variable? would it be a value with a combination of upper,lower case,punctuation and digits with any length btwn 8 and 16?

is there any easier way to make password generator using python program?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Maverick
  • 119
  • 1
  • 10

1 Answers1

3

If you print characters you will get a list of characters and symbols.

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~0123456789

The next line is going to use this assortment of characters to randomly select from. Adding or removing characters would allow you to customize the characters that make up the password.

You can read up on the join, choice and randint functions with a quick google search. It might make more sense if this code was broken up into more lines and variables. There's quite a bit of short hand smushed into a single line.

import string
import random
characters = string.ascii_letters + string.punctuation  + string.digits

password = ""
password_length = random.randint(8, 16)

for x in range(password_length):
    char = random.choice(characters)
    password = password + char

print password
abaldwin99
  • 903
  • 1
  • 8
  • 26
  • what is the use of giving from random import * ? can i give it just 'import random' ? – Maverick Aug 02 '15 at 19:09
  • you can use import random and that is the more pythonic way to do things... that way you know what methods come from what library. If you us `import random` you would need to change `choice` to `random.choice`. See revised answer. – abaldwin99 Aug 02 '15 at 19:11
  • initially there would be null value stored in password variable? – Maverick Aug 02 '15 at 19:22
  • @ abaldwin99..thnk u for ur input – Maverick Aug 02 '15 at 19:35
  • The password variable is an empty string initially. Python has a value of `None` but an empty string is inherently different from that. – abaldwin99 Aug 02 '15 at 20:15
  • Folks,i have 1 more questions... how can i include only few special characters instead of using string.punctuation? for example i want to include only !@#$% in password generator... – Maverick Aug 03 '15 at 04:43