Day 28: A Simple Password Generator With random.choice()

What is the most elegant way to choose a random char from a string, list or tuple?

 

It’s random.choice(some_string)

 

I build a simple password generator that will build a password the length the user has chosen.

 

If the length is smaller than 8 though the user will have to redo his entry.

 

This is what the output looks like:

 

 

This is what the code looks like:

 

# A simple password generator
# creates a random String
# will ask anew if length was too short


import random

# the string contains all the chars we want to use.
alphabet = "1234567890abcdefghijklmnopqrstuvwxyz!@#$%^&<>?ABCDEFGHIJKLMNOPQRSTUVWXYZ"


def pass_gen(pass_length):
    i = 1
    password = ""
    
    if (int(pass_length) >= 8):
        while i <= int(pass_length):
            # random.choice() is the shortest and lean way
            # to select a random char from a string, list or tuple
            password = password + random.choice(alphabet)
            i += 1
    else:
        pass_gen(input("Chosen length too short. Enter a length (min 8): "))

    print(password)

pass_gen(input("Enter the maximum length of your password (min 8): "))

You find more information about random.choice() here.