Random Number generator

Generating random integer between a range , 1(inclusive ) and 10 ( inclusive )
import random
print(random.randint(1,10))
Output
3
Displaying 10 random integers between 0 and 10
import random
for x in range(10):
  print(random.randint(0,10),', ',end='')
Output
4 , 0 , 3 , 10 , 2 , 6 , 7 , 3 , 4 , 7 ,  

randrange

Random number between a range. ( start , stop [,step])
from random import randrange
print(randrange(10)) # From  0 to 9 
Output
3

Random float

We can generate float between 0 and less than 1 ( exclusive )
import random
print(random.random()) # between 0 and less than 1 
Output
0.6919994035378282

uniform

Random float between a range of numbers
random.uniform(1.2, 2.3) # start and stop , both inclusive 
Output
1.7852514538737663
We used random.random() and random.uniform for generating random float numbers. The main difference between them are here.

random.uniform takes two parameters start and stop to return number within the range. random.random() takes no parameter and returns between 0.0 and 1. (It will return less than 1. )

random.uniform() returns between start and stop ( inclusive )

Example

Use one function to generate marks for a class. Input to the function will be the number of students in the class. A student can secure marks between 0 and 100.
def gen_marks(student_no):
    my_list=[]
    for i in range(student_no):
        my_list.append(random.randint(0,101))
    return my_list
	
class_4=gen_marks(28) # Marks of class 4 for 28 students


plus2net.com



Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer