Python

Python Random

Python Random

In Python, there is a built-in module “random“. The module providers random number generators.

The module offers many useful built-in functions. such as generating random numbers or selecting randomly elements from a data type.

This tutorial covers only a part of the methods, focusing on the most common and useful ones.

  • random()
  • randint()
  • choice()
  • sample()
  • choices()
  • shuffle()
  • seed()

Please note that the module needs importing first.

Random()

The method of “random()” returns a random float number between 0 and 1.

import random

print(random.random())

# Output: 0.14062818562529378

Randint()

As the name suggests, “randint()” returns a random integer number between a given range.

import random

print(random.randint(1, 20))

# Output: 16

Choice()

The method “choice()” returns a random item from a data type.

import random

someTuple = ("red", "blue", "green")

print(random.choice(someTuple))

# Output: blue

Sample()

The method “sample()” extends “choice()”, by allowing multiple samples.

The letter “k” selects the number of samples. The output is a list.

import random

someTuple = ("red", "blue", "green")

print(random.sample(someTuple, k=2))

# Output: ['green', 'blue']

Choices()

The method “choices()” extends both “choice()” and “sample()” even further.

It returns a random selection from a data type.

The keyword “weights” ranks each item (in terms of selection probability). The letter “k” selects the number of outcomes.

import random

someTuple = ("red", "blue", "green")

print(random.choices(someTuple, weights = [1, 6, 1], k=9))

# Output: ['blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'red', 'green', 'blue']

The chance of s electing the colour blue is 6 times higher than red or green. This is the reason why both red and green appear only once.

Shuffle()

As the name suggests, the method “shuffle()” shuffles a sequence and returns the outcome randomly.

import random

someList = [1, 2, 3, 4, 5, 6, 7]
random.shuffle(someList)

print(someList)

# Output: [7, 1, 4, 6, 5, 2, 3]

Seed()

The method “seed()” implements an initialisation of a random generator.

This means that any two seed values with the same number will generate the same outcome.

import random

random.seed(3)
print(random.randint(1, 100))

# Output: 31

Let’s test it with two random number generators, both with the same seed value.

import random

random.seed(3)
print(random.randint(1, 100))

random.seed(3)
print(random.randint(1, 100))

# Output: 31
# Output: 31

Next: Python Advanced Functions

by AICorr Team

We are proud to offer our extensive knowledge to you, for free. The AICorr Team puts a lot of effort in researching, testing, and writing the content within the platform (aicorr.com). We hope that you learn and progress forward.