Python : generate a random number with a specific number of digits

Here is a simple Python function that generates a random number with the number of digits specified by the user:

import random

def generate_random_number(num_digits):
    min_range = 10**(num_digits-1)
    max_range = 10**num_digits - 1
    return random.randint(min_range, max_range)

# Test the function
print(generate_random_number(3))  # Outputs a random 3-digit number
print(generate_random_number(5))  # Outputs a random 5-digit number

This function uses the `randint()` function from the `random` module to generate a random integer between the minimum and maximum range for the number of digits specified by the user. The minimum range is calculated as `10` raised to the power of `num_digits - 1`, and the maximum range is calculated as 10 raised to the power of `num_digits` minus `1`. For example, if the user specifies `3` digits, the minimum range will be `100` and the maximum range will be `999`.

Leave a Reply