CBSE Class 12 Computer Science
Question 101 of 103
Working with Functions — Question 7
Back to all questions 7
Question Write a function that takes a number n and then returns a randomly generated number having exactly n digits (not starting with zero) e.g., if n is 2 then function can randomly return a number 10-99 but 07, 02 etc. are not valid two digit numbers.
import random
def generate_number(n):
lower_bound = 10 ** (n - 1)
upper_bound = (10 ** n) - 1
return random.randint(lower_bound, upper_bound)
n = int(input("Enter the value of n:"))
random_number = generate_number(n)
print("Random number:", random_number)Enter the value of n:2
Random number: 10
Enter the value of n:2
Random number: 50
Enter the value of n:3
Random number: 899
Enter the value of n:4
Random number: 1204