6.1 random Module
A module is a reusable collection of Python code. Python's built-in collection of modules is called the standard library. The random module provides tools for random numbers, random choices, and shuffling.
Importing a Module
Import a module before using it.
python
import random
print(random.random())
print(random.randint(1, 6))random.random() returns a random floating-point number in [0, 1). random.randint(1, 6) returns an integer from 1 through 6, including both endpoints.
Loading concept check...
Common random Methods
Common random methods:
random(): generate a floating-point number in[0, 1).randint(a, b): generate an integer in[a, b].choice(sequence): choose one element from a sequence.shuffle(list): shuffle a list in place.sample(sequence, k): choosekunique elements and return a new list.
Note that shuffle() mutates the original list, while sample() returns a new list.
Random Password Generator
A password generator prepares a character pool, chooses a length, repeatedly chooses random characters, and joins them into a string.
Loading interactive lab...
python
import random
import string
def password_generator(length):
characters = string.ascii_letters + string.digits
return "".join(random.choice(characters) for _ in range(length))
def main():
length = int(input("Enter password length: "))
print("Random password: %s" % password_generator(length))
if __name__ == "__main__":
main()One possible run:
text
Enter password length: 8
Random password: K2bm9Qa1Loading concept check...
Loading practice...