How to get a random number in python?

Random numbers can be generated in python by using the random module. The random module performs some actions randomly such as selecting random elements from a list, getting a random number, returns the sequence in a random order, etc.

The random() module comes with a various built-in function such as random(), randint(), randrange(), etc. The article discusses different methods to generate random numbers.

Generating a random float number using the random() method

The random() method returns a random float number between 0 to 1 and doesn't take any arguments. Consider the given example, to generate a float number.

import random



Generating a random integer number using the randint() method

The randint() method returns a random integer between a specified range. It takes two parameters starting value and ending value. Consider the given example to generate a number in the range of 10 to 20.

import random



Generating a random integer number using the randrange() method

The randrange() method is similar to the randint() method but requires three arguments start, stop and step. The value for start is 0 by default and step is 1 by default. Consider the given example to generate odd numbers.

import random



Selecting a random number using the choice() method

A sequence(list, tuple, set, etc) is passed as an argument to choice() function. The choice() method selects a random item from the sequence and returns the value. For example,

import random
print(random.choice([3, 4, 5.5, 8]))


0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions