[Type C] Working with Functions – Chapter 3 Sumita Arora

|
Table of Contents

7. Write a function that takes a number n and then returns a randomly generated number having exactly n digits (not starting with zero). For example, if n is 2, then the function can randomly return a number 10-99, but 07, 02, etc., are not valid two-digit numbers.

Short Answer: The function generates a random number with exactly n digits (excluding leading zeros) and returns it.

Python
import random

def generate_random_n_digit_number(n):
    min_value = 10 ** (n - 1)
    max_value = (10 ** n) - 1
    return random.randint(min_value, max_value)

# Test
print(generate_random_n_digit_number(2))  # Example output: 42

Explanation:

  • The function generate_random_n_digit_number generates a random integer within the range of n-digit numbers (excluding leading zeros) using random.randint.
  • The minimum value is calculated as 10^(n-1) and the maximum value as (10^n) – 1, ensuring the generated number has exactly n digits.
  • Test case demonstrates the usage of the function to generate a random two-digit number.
"Spread the light within, illuminate the hearts around you. Sharing is not just an action, but a sacred journey of connecting souls."~ Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *