You Might Have Misused Python Random

Photo by Lucas Santos on Unsplash


Basic usage of Python random module

#Generate a random integer between 1 to 10 
#generate a random floating point number between 0 to 1 random.random()
#Generate random number between 1 to 2 in uniform distribution
random.uniform(1, 2)
#Generate random number between 1 to 100, with step as 2
random.randrange(1, 100, 2)
#Generate random bytes, available in Python version 3.9 random.randbytes(8)
#Generate a integer within 8 bits
slangs = ["Boomer", "Cap", "Basic", "Retweet", "Fit", "Fr", "Clout"]random.shuffle(slangs) 
#['Fit', 'Basic', 'Fr', 'Clout', 'Cap', 'Retweet', 'Boomer']

random.sample(slangs, k=5)
#['Fit', 'Fr', 'Clout', 'Retweet', 'Basic']
random.choice(["Boomer", "Cap", "Basic", "Retweet", "Fit", "Fr", "Clout"])

Why the random numbers generated are not random enough?

sys_random = random.SystemRandom()sys_random.random() 
sys_random.randint(1, 100)
sys_random.choice(["Boomer", "Cap", "Basic", "Retweet", "Fit", "Fr", "Clout"])

Python secrets module

#Generate random integer between 0 to 50 
#Generate random integer with 8 bits
#Generate random bytes
#Generate random string in hexadecimal with default 32 bytes
#Generate URL-safe text string
import string secrets.choice(string.ascii_letters + string.digits + string.punctuation)

Implementing a strong password generator with Python secrets

def generate_strong_password():    special_characters = '!#$%&@_~' 
password_choices = string.ascii_letters + string.digits + special_characters
while True:
password = ''.join(secrets.choice(password_choices) for _ in range(random.randint(8, 16)))
if (any(c.islower() for c in password)
and any(c.isupper() for c in password)
and sum(special_characters.find(c) > -1 for c in password) == 1
and any(c.isdigit() for c in password)):

return password
[generate_strong_password() for _ in range(10)] # sample output 


Resources and tutorials for python, data science and automation solutions

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store