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
forxinrange(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
without repeating numbers
Without duplicate numbers we can generate from 1 to 100 ( 10 numbers selected )
print(random.sample(range(1, 100), 10))
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.
defgen_marks(student_no):
my_list = []
foriinrange(student_no):
my_list.append(random.randint(0, 101))
returnmy_listclass_4 = gen_marks(28) # Marks of class 4 for 28 students
random string
Length of 6 chars , all lowercase. Change the char to Uppercase by using ascii_uppercase