Python random function

 Python random function :

Python has another important function which is random() , to generate random number . 

To use random function , we have to import the module . 

 import random  
  • randrange() function :
This method always return integer value with specific range . 

    randrange(start,stop,step)
start  ==> Starting point , by default zero , only integer value .
stop  ==> Does not return this value and it is mandatory , only integer value .
step  ==> Not mandatory

Example :

 Input :  
 >>> import random  
 >>>print(random.randrange(5))  
 >>>printr(random.randrange(5))  
 >>>print(random.randrange(1,10,2))  
 >>>print(random.randrange(1,10,2))  
 >>>print(random.randrange(2,6))  
 >>>print(random.randrange(2,6))  
 Output :  
 >>>2  
 >>>3  
 >>>6  
 >>>9  
 >>>2  
 >>>5  
  • random() function :
Returns random number between 0 and 1 .
 Input :  
 >>> import random  
 >>> print(random.random())  
 >>> print(random.random())  
 Output :  
 >>> 0.3137831859161889  
 >>> 0.9377467713591402  
  • randint() function:
randint(start ,stop)
     This functions returns any integer between starting point and stopping point , include both points .

 Input :  
 >>> import random  
 >>> print(random.randint(5,10))  
 >>> print(random.randint(5,10))  
 Output :  
 >>> 10  
 >>> 6  
  • uniform() function :
uniform(start ,stop)

start  ==>It takes both integer and floating number . Starting point is included .

stop  ==> Also it take both integer and floating value  . Stopping point is excluded .

Returns always floating number .


 Input :  
 >>> import random  
 >>> print(random.uniform(5.2,10))  
 >>> print(random.uniform(2,7.8))  
 Output :  
 >>> 8.475143256695208  
 >>> 6.515120444340265  

  • choice() function :
This method is used for random selection from list , tuple and string .

Example :

 Input :  
 >>> # lets create a string  
 >>> a="Hello World !"  
 >>> import random  
 >>> print(random.choice(a))  
 Output :  
 >>> o  
 >>>    """This will return different  
         character from the string , output will always different ."""  
Share:

2 Comments

For query , suggestion and others , please comment below. Don't share external link or spam on comment box . 💌

  1. Please update next part of this post

    ReplyDelete
    Replies
    1. I hope you like our blogging. Thanks for your interest . We are trying our best. very soon update will be visible . Please bookmark our website ,and visit.

      Delete
Previous Post Next Post