Random Module

Advanced PythonUtilitiesFree Lesson

Advertisement

Introduction

The random module generates pseudo-random numbers for games, simulations, and testing.

Basic Random

import random

random.random()        # Float in [0, 1)
random.randint(1, 10) # Integer in [1, 10]
random.randrange(0, 100, 2)  # Even numbers 0-98

Sequences

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

random.choice(lst)           # Single random element
random.choices(lst, k=3)    # Multiple with replacement
random.sample(lst, k=3)     # Multiple without replacement
random.shuffle(lst)         # In-place shuffle

Distributions

import random

random.gauss(0, 1)     # Gaussian/normal distribution
random.uniform(0, 1)   # Uniform distribution
random.triangular(0, 1)  # Triangular distribution

# Weighted choices
weights = [0.1, 0.2, 0.3, 0.4]
random.choices(lst, weights=weights)

Practice Problems

  1. Generate random password
  2. Shuffle deck of cards
  3. Simulate dice rolls
  4. Generate weighted random samples
  5. Create random walk simulation

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement