Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

To generate a random number with a specific number of digits in Python, you can use the following code:
Python logo Python logo
Python logo

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`.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading