Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Random Number Generation

Python Random Number Generation

Document Object Reference Manual Python3 Examples

In Python, the built-in random module can be used to generate random numbers.

import random

random.random()

random.random() returns a random decimal between 0.0 and 1.0:

Example

import

random

random_number

=

random

.

random

(

)

print

(

random_number

)

The output of the code above is:


0.7597072251250637

random.randint(a, b)

random.randint(a, b) returns an integer between a and b (including both a and b).


random.randint(a,b)

The function returns a number N, where N is a number between a and b (a <= N <= b), including a and b.

The following example shows how to generate a random number between 0 and 9:

Example

-- coding: UTF-8 --

Filename : test.py

author by : www.runoob.com

Generate a random number between 0 and 9

Import the random (random number) module

import

random

print

(

random

.

randint

(

0

,

9

)

)

The output of the code above is:


4

random.choice(sequence)

random.choice(sequence) is used to randomly select an element from a sequence:

Example

import

random

list1

=

[

1

,

2

,

3

,

4

,

5

]

random_element

=

random

.

choice

(

list1

)

print

(

random_element

)

Example

import

random

list1

=

[

1

,

2

,

3

,

4

,

5

]

random_element

=

random

.

choice

(

list1

)

print

(

random_element

)

The output of the code above is:


4

random.shuffle(sequence)

random.shuffle(sequence) is used to randomly shuffle the elements in a sequence:

Example

import random

list1 = [1, 2, 3, 4, 5]

random.shuffle(list1)

print(list1)

The output of the code above is:


[3, 2, 4, 5, 1]

Document Object Reference Manual Python3 Examples