Python Random Number Generation

Document 对象参考手册Python3 Examples

In Python, you can use the built-in random module 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)

Executing the above code produces the following output:

0.7597072251250637

random.randint(a, b)

random.randint(a, b) is used to return an integer between a and b (inclusive of a and b).

random.randint(a,b)

The function returns a number N, which is between a and b (a <= N <= b), inclusive of a and b.

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

Example

# -*- coding: UTF-8 -*- # Filename : test.py # author by : www.example.com # Generate a random number between 0 and 9 # Import the random module import random print(random.randint(0,9))

Executing the above code produces the following output:

4

random.choice(sequence)

random.choice(sequence)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)

Executing the above code produces the following output:

4

random.shuffle(sequence)

random.shuffle(sequence)Used to randomly sort the elements in a sequence:

Example

import random

list1 = [1, 2, 3, 4, 5]
random.shuffle(list1)
print(list1)

Executing the above code produces the following output:

[3, 2, 4, 5, 1]

Document 对象参考手册Python3 Examples

Other Extensions