random
The random module implements pseudo-random number generators for various distributions.
Generate a random integer
import random
print(random.randint(1, 9999)) # 7438
print(random.randint(1, 9999)) # 2513
print(random.randint(1, 9999)) # 8846
Make a random string
import random
import string
candidates = string.ascii_lowercase
# make a random string of length 10
result = ''.join(random.choice(candidates) for _ in range(10))
print(result) # kcxgdhpvpp
# make a random string of length 20
candidates = string.ascii_letters + string.digits
result = ''.join(random.choice(candidates) for _ in range(20))
print(result) # bDZ6ircqadMZfoHDM6yZ
Generate a float with Gaussian distribution
import random
mu, sigma = 2, 0.2
print(random.gauss(mu, sigma)) # 2.2689935909942758
print(random.gauss(mu, sigma)) # 2.3242305820201996
print(random.gauss(mu, sigma)) # 1.9878185078852277
mu
is the mean, and sigma
is the standard deviation.
Pick multiple elements randomly
import random
students = ['Alice', 'Bob', 'Cindy', 'Doug']
print(random.choices(students, k=2)) # ['Doug', 'Cindy']
print(random.choices(students, k=2)) # ['Cindy', 'Bob']
print(random.choices(students, k=2)) # ['Alice', 'Alice']
choices(population, ..., k=1)
returns a k sized list of elements chosen from the population with replacement.
Code Challenge
Try to modify the code in the editor to make a
secure
enough password.
Loading...
> code result goes here