Python Random Module

The random module is used to generate random numbers and make random selections. It is commonly used in games, simulations, and testing applications. Importing the Random Module Example randint() The randint() function returns a random integer between the specified range. Syntax Example Output: Output may vary each time. randrange() The randrange() function returns a random […]

2 mins read Lesson 39 of 56 70% through track

The random module is used to generate random numbers and make random selections. It is commonly used in games, simulations, and testing applications.

Importing the Random Module

Example

import random

randint()

The randint() function returns a random integer between the specified range.

Syntax

random.randint(start, end)

Example

import random

print(random.randint(1, 10))

Output:

7

Output may vary each time.

randrange()

The randrange() function returns a random number from a specified range.

Example

import random

print(random.randrange(1, 20))

Output:

12

Output may vary each time.

random()

The random() function returns a random floating-point number between 0 and 1.

Example

import random

print(random.random())

Output:

0.684321

Output may vary each time.

choice()

The choice() function returns a random item from a sequence.

Example

import random

fruits = ["apple", "banana", "mango"]

print(random.choice(fruits))

Output:

banana

Output may vary each time.

choices()

The choices() function returns multiple random items.

Example

import random

fruits = ["apple", "banana", "mango"]

print(random.choices(fruits, k=2))

Output:

['banana', 'apple']

Output may vary each time.

shuffle()

The shuffle() function randomly rearranges the items in a list.

Example

import random

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

random.shuffle(numbers)

print(numbers)

Output:

[3, 1, 5, 2, 4]

Output may vary each time.

uniform()

The uniform() function returns a random floating-point number within a specified range.

Example

import random

print(random.uniform(1, 10))

Output:

5.72

Output may vary each time.

seed()

The seed() function generates the same random values every time for testing purposes.

Example

import random

random.seed(10)

print(random.randint(1, 100))

Output:

74

Summary

  • The random module is used to generate random values.
  • randint() returns a random integer within a range.
  • randrange() returns a random number from a range.
  • random() returns a float between 0 and 1.
  • choice() selects a random item from a sequence.
  • choices() selects multiple random items.
  • shuffle() randomly rearranges a list.
  • uniform() returns a random floating-point number within a range.
  • seed() is used to generate predictable random results.