1. Introduction to the random module
1.1. Introduction to random module
The random module is a module used in the Python standard library to generate pseudo-random numbers. Pseudo-random numbers are sequences generated by algorithms that exhibit randomness within a certain range. Although these sequences are predictable to a certain extent, they are sufficient for most applications.
2. The basic functions of random module
2.1. Use functions for integers
2.1.1、()
(start, stop[, step])
Returns an element randomly selected from range(start, stop, step).
Supports setting step sizes, and can generate random numbers at fixed intervals, which is useful for random numbers that require a specific pattern or interval. Note: The right border is not included
# Returns random integers in the range 0 <= N < 100print((100)) # Returns random integers in the range 100 <= N < 200print((100, 200)) # Returns a random integer in the range 100 <= N < 200, with a step size of 5print((100, 200, 5))
2.1.2、()
(a, b)
Returns the random integer N satisfies a <= N <= b. Equivalent to randrange(a, b+1).
Setting step size is not supported, and only any integer within the specified range can be generated. Note: Includes the left and right boundaries
# Returns random integers in the range 100 <= N <= 200print((100, 200))
2.1.3、()
(k)
Returns the random integer N satisfies 0 <= N <= 2^k-1. For example, getrandbits(16) will generate a random integer between 0 and 65535. This function is especially suitable for situations where a large range of random numbers is needed.
# Return 0 <= N <= 65535 (2 to the 16th power and subtract 1) random integers in the rangeprint((16))
2.2. Use functions for sequences
2.2.1、()
(seq)
Returns a random element from a non-empty sequence seq. If seq is empty, an IndexError is raised.
a = ['alice', 'bob', 'helen', 'jack', 'sue'] b = ('alice', 'bob', 'helen', 'jack', 'sue') c = {'alice', 'bob', 'helen', 'jack', 'sue'} d = {'alice': 16, 'bob': 18, 'helen': 19, 'jack': 20, 'sue': 22} e = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # Select an element randomly from the listprint((a)) # Select an element randomly from a tupleprint((b)) # Select an element randomly from a stringprint((e)) # ——————————————————————————————————————————— # Random selection from the collection is not supported, an error will be reported# print((c)) # Random selection from the dictionary is not supported, and an error will be reported, but it can be implemented using the (list(())) method.# print((d))
2.2.2、()
(population, weights=None, *, cum_weights=None, k=1)
- population: Required parameter, specifying the sequence to be selected (can be list, tuple, string, etc.).
- weights: Optional parameter, specifying the weight (probability) of each element. If not specified, the weights of each element are defaulted to be equal.
- cum_weights: Optional parameter, specifying the accumulated weight. If cum_weights is specified, the weights parameter must be omitted.
- k: Optional parameter, specifying the number of elements to be selected. The default is 1, which means only one element is selected.
K elements are randomly extracted from the sequence, and the corresponding array is returned. The weights parameter represents the relative weight selected by each element, while cum_weights represents the cumulative weight, and their lengths must be consistent with the length of the sequence to be extracted. If no weight is set, the weight drawn by each element is the same.
Note: The weight cannot be negative, otherwise an error will be reported.
import random fruits = ['apple', 'banana', 'orange', 'grape', 'watermelon'] weights = [0.1, 0.2, 0.3, 0.2, 0.2] cum_weights = [0.1, 0.4, 0.7, 0.9, 1.0] # Select an element randomly from the listchosen_fruit = (fruits) # Select multiple elementschosen_fruits = (fruits, k=3) # Select an element randomly from the list by probabilitychosen_fruit = (fruits, weights=weights) # Use cum_weights parameter to select elementschosen_fruit = (fruits, cum_weights=cum_weights)
Select multiple elements and count the number of selected times
import random fruits = ['apple', 'banana', 'orange', 'grape', 'watermelon'] chosen_fruits = (fruits, k=1000) fruit_counts = {} for fruit in chosen_fruits: if fruit in fruit_counts: fruit_counts[fruit] += 1 else: fruit_counts[fruit] = 1 print(fruit_counts)
2.2.3、()
(x)
Randomly disrupt the position of the sequence x in place.
import random fruits = ['apple', 'banana', 'orange', 'grape', 'watermelon'] (fruits) # Note: The original list has been changedprint(fruits) # ['orange', 'watermelon', 'grape', 'banana', 'apple']
2.2.4、()
(population, k, *, counts=None)
Randomly extract k elements from the sequence without putting back. For random sampling without repetitions.
import random fruits = ['apple', 'banana', 'orange', 'grape', 'watermelon'] # Return a new random disrupted sequence, Note: The original list has not changedprint((fruits,len(fruits))) # ['orange', 'watermelon', 'apple', 'banana', 'grape'] print(fruits) # ['apple', 'banana', 'orange', 'grape', 'watermelon']
Repeated elements can be listed directly one by one, or specified using the optional keyword-only parameters counts. For example, sample(['red', 'blue'], counts=[4, 2], k=5) is equivalent to sample(['red', 'red', 'red', 'red', 'red', 'blue', 'blue'], k=5).
To select a sample from a series of integers, use the range() object as an argument. For sampling from large populations, this method is particularly fast and space-saving: sample(range(10000000), k=60) .
2.3. Discrete distribution
2.3.1、()
(n=1, p=0.5)
Binomial distribution. Returns the number of successes of n independent trials when the success rate of each trial is p
2.4. Real value distribution
2.4.1、()
()
Returns random floating point numbers in the range 0.0 <= X < 1.0
2.4.2、(a, b)
(a, b)
Returns a random floating point number N, a <= N <= b.
import random print((60, 100))
2.4.2.1. Method of retaining n positions after the decimal point
2.4.2.1.1. Use the round() function
num = 3.14159 # This method is roundingrounded_num = round(num, 2) # Output: 3.14
2.4.2.1.2. Use the format() function
num = 3.14159 # This method is rounding, note: what you get is a floating point number in the form of a stringformatted_num = "{:.2f}".format(num) # Output: '3.14'
2.4.2.1.3. Use the decimal module for precise control
from decimal import Decimal, ROUND_HALF_UP num = Decimal('3.14159') context = Decimal(1) / Decimal(10) ** 2 # This method is roundingrounded_num = (context, rounding=ROUND_HALF_UP) # Output: Decimal('3.14')
2.4.2.1.4. Use f-string (Python 3.6+)
num = 3.14159 formatted_num = f"{num:.2f}" # Output: '3.14'
3. Random-related modules
3.1. Secrets module
The secrets module is used to generate highly encrypted random numbers suitable for managing passwords, account verification, security credentials and confidential data.
3.1.1、()
(seq)
Returns an element selected randomly from a non-empty sequence.
import secrets # Suppose we have a list of elementsfruits = ['apple', 'banana', 'orange', 'grape', 'watermelon'] # Use to safely select a random element in the listsecure_random_element = (fruits) print(secure_random_element)
3.1.2、()
(exclusive_upper_bound)
Returns a random integer in the range [0, exclusive_upper_bound).
import secrets # Generate a safe random integer with a range of 0 <= N < 10secure_int = (10) print(f"Safe random integers:{secure_int}")
3.1.3、()
(k)
Returns a non-negative integer with k random bits. For example (3), it means that the value is 0 <= N < 2^3, that is, a random integer between [0, 8).
3.1.4、secrets.token_bytes()
secrets.token_bytes([nbytes=None])
If nbytes is specified, secrets.token_bytes(nbytes) returns a bytes object containing nbytes random bytes. If the nbytes parameter is not provided, it returns a random sequence of bytes (usually 32 bytes) that corresponds to the default length applicable to the security token.
import secrets # Generate a random byte sequence of default length (usually 32 bytes)random_token = secrets.token_bytes() print(len(random_token)) #Output: 32print(random_token) # Output random byte sequence: b'<\xa1\xc2\xb9k\xf4\x9e$\xd9\x03\xd5H\xb8\x1e\xe2d\xe0\x82x\xe9)\x11\xe9\x04l\xda\x95\xe3\xf0C\x88\xba'# Generate a random sequence of bytes of a specified lengthspecified_length_token = secrets.token_bytes(16) print(specified_length_token) # Output a random byte sequence:b'\xa2C\x98H\xb2\xca5\n\xb69h{\xfa\xb3n\xc5'
3.1.5、secrets.token_hex()
secrets.token_hex([nbytes=None])
If the nbytes parameter is provided, a hexadecimal string of length nbytes*2 is generated (each byte is converted to two hexadecimal characters). If the nbytes parameter is not provided, a hexadecimal string (usually 32 characters) is generated for the default length of the security token.
import secrets # Generate a random hexadecimal string of default length (usually 32 characters)random_hex_token = secrets.token_hex() print(random_hex_token) # 53063bd5d38f7f032e146d769567254748dcbc34de37f716043a21d4b9ef0575 # Generate a random hexadecimal string of specified lengthspecified_length_hex_token = secrets.token_hex(16) print(specified_length_hex_token) # bcce543dee60747639895e2fcffcfaf8
3.1.6、secrets.token_urlsafe()
secrets.token_urlsafe([nbytes=None])
Returns a secure URL random text string containing nbytes random bytes. Text is encoded with Base64, and on average, each byte corresponds to 1.3 result characters. When nbytes is not provided or None, it generates a random URL secure string of default length suitable for security tokens. The return value generated by this function is a string containing only URL-safe characters (letters, numbers, underscores, and short horizontal lines).
import secrets # Generate a random URL secure string of default lengthrandom_urlsafe_token = secrets.token_urlsafe() print(len(random_urlsafe_token)) # Output: 43print(random_urlsafe_token) # Output: t6GrND8P32pL763R36VQIaB70jf8r_uruvSa0wgQYrY# Generate a random URL secure string of specified lengthspecified_length_urlsafe_token = secrets.token_urlsafe(16) print(specified_length_urlsafe_token) # Output:dUA2mPJbbWtB6rLj8hoC1g
3.1.7、secrets.compare_digest()
secrets.compare_digest(a, b)
Used to compare two strings a and b, and have the characteristics of preventing time-side channel attacks when string matching. In cryptography and security-related scenarios, using secrets.compare_digest is better than the simple == operator when comparing two sensitive strings. This function returns a Boolean value, if a and b match, True, otherwise False. This comparison is more uniform in comparison time and is less susceptible to time-side channel attacks. Using this function when comparing sensitive data, especially when using password verification or token comparison, can improve the security of the system.
Generate system password example
import string import random import secrets def generate_password(min_length, max_repeat, max_class_repeat, *char_credits): characters = [, string.ascii_uppercase, '!@#$%^&*(){}<>,?`~+-=[]', string.ascii_lowercase] all_characters = ''.join(characters) while True: # Generate characters for each character category password = [(char) for char, count in zip(characters, char_credits) for _ in range(count)] # Add characters to meet minimum password length requirements remaining_len = min_length - sum(char_credits) password += [(all_characters) for _ in range(remaining_len)] (password) if is_valid_password(min_length, password, characters, max_repeat, max_class_repeat): return ''.join(password) def is_valid_password(min_length, password, characters, max_repeat, max_class_repeat): # determine whether it starts with = if ''.join(password).startswith("="): return False # Check whether characters and categories are repeated continuously for more than the specified number of times repeat_count = max((char) for char in set(password)) if repeat_count > min_length // 4: return False for char_class in characters: char_class_positions = [idx for idx, char in enumerate(password) if char in char_class] for idx in char_class_positions: if idx < len(password) - max_class_repeat: if all(password[idx + i] in char_class for i in range(0, max_class_repeat + 1)): return False # Determine the index of the same character char_repeat = [char for char in set(password) if (char) > max_repeat] char_repeat_positions = {} for idx, char in enumerate(password): if char in char_repeat: if char not in char_repeat_positions: char_repeat_positions[char] = [idx] else: char_repeat_positions[char].append(idx) # Determine whether the same characters are continuous for _, index in char_repeat_positions.items(): for idx in index: if idx < len(password) - max_repeat: if all(password[idx + i] == password[idx] for i in range(0, max_repeat + 1)): return False return True if __name__ == '__main__': # Set the parameters for password generation min_length = 16 char_credits = (3, 3, 3, 3) # Numbers, capital letters, special characters, lowercase letters # The number of characters that cannot be repeated continuously max_repeat = 2 # The number of characters that cannot be repeated in succession max_class_repeat = 3 # Generate and print passwords for _ in range(100): generated_password = generate_password(min_length, max_repeat, max_class_repeat, *char_credits) print(generated_password)
Generate password reset URL example
import secrets import string # Generate security tokens for password recovery applicationssecurity_token = ''.join((string.ascii_letters + ) for _ in range(16)) # Build a temporary security URLtemp_url = f"/password-recovery?token={security_token}" print("The generated temporary security URL:", temp_url) # Output:Generated temporary securityURL: /password-recovery?token=90HOEUVFroaJIO5D
This is the end of this article about the detailed explanation of the use of Python random module. For more related content of Python random module, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!