Random Numbers

The random module can be used to make random numbers in Python. The function random() generates a number between 0 and 1.

Online Courses

Generate random nubers

Generate a real number between 0 and 1
Simply call the random() method to generate a real (float) number between 0 and 1.

import random
x = random.random()

Generate a number between 0 and 50
We use the randint() method to generate a whole number.

import random
x = random.randint(0,50)

Generate a random number between 1 and 10
Change the parameters of randint() to generate a number between 1 and 10.

import random
x = random.randint(1,10)

List of random numbers

To generate a list of 100 random numbers:

import random

list = []

for i in range(0,100):
    x = random.randint(1,10)


Choosing random items from a list

To get 3 random items from a list:

import random

list = [1,2,3,4,5,6,7,8,9,10]
x = random.sample(list,3)
Previous Post
Next Post

Leave a Reply

Your email address will not be published. Required fields are marked *