Q. Write a function that takes a number n and then returns a randomly generated number having exactly n digits (not starting with zero)

eg ., if n is 2 then function can randomly return a number 10-99 but 07, 02 etc. are not valid two digit numbers.


You can understand by Watching video :-



Answer:-

import random

def ran( x ) :
    a = 10 ** (x - 1 )
    b= 10 ** (x )
    print( random.randint ( a , b ) )

n = int(input("Enter number of digit : "))

ran(n)

Output :-

Enter number of digit : 2
72

>>> 

Enter number of digit : 9
638330587

>>> 

Enter number of digit : 5
75450

>>> 

Enter number of digit : 10
5498667849

>>> 

Enter number of digit : 100
4655969082985716754399543003519602906342699471049675327533099576946492019622835421434523706415649864
>>> 



8 Comments

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

  1. What if the user enters 0???

    ReplyDelete
    Replies
    1. It will give error because zero digit number is not possible.

      Delete
  2. Abhishek Kushwaha30 June 2023 at 18:01

    Traceback (most recent call last):
    File "C:/Users/ak892/AppData/Local/Programs/Python/Python311/abhui.py", line 7, in
    abhi(x)
    File "C:/Users/ak892/AppData/Local/Programs/Python/Python311/abhui.py", line 5, in abhi
    print(random.randint(a,b))
    ValueError: Exceeds the limit (4300) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit

    ReplyDelete
  3. I think it should be randrange() instead of rangeint()

    ReplyDelete

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post