Skip to main content

How to Generate Random Numbers in Python

How to Generate Random Numbers in Python | Rustcode

How to Generate Random Numbers in Python

Random number generation is essential for simulations, games, data sampling, testing, and more. Python offers convenient and powerful ways to generate random numbers through its random module. From simple integers to floating-point numbers and random selections, here's how you can generate random numbers in Python with practical examples and clear explanations.


Why Generate Random Numbers?

  • Simulations: Model unpredictable processes like dice rolls or lottery draws.
  • Games: Randomize events, choices, or enemies.
  • Sampling & Testing: Select random samples or create randomized test data.

01. Importing the random Module

import random

02. Generate a Random Integer

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

import random

# Generate a random integer between 1 and 100
num = random.randint(1, 100)
print(num)

Output:

73

03. Generate a Random Float

random.random() returns a float between 0.0 and 1.0 (not including 1.0).

import random

# Random float from [0.0, 1.0)
num = random.random()
print(num)

Output:

0.531234987911

random.uniform(a, b) returns a float between a and b.

num = random.uniform(10, 20)
print(num)

04. Random Choice from a Sequence

random.choice() selects a random element from a list, tuple, or string.

import random

colors = ['red', 'green', 'blue']
choice = random.choice(colors)
print(choice)

Output:

blue

05. Advanced: Shuffle, Sample, and More

random.shuffle() randomly rearranges elements in a list.

import random

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

random.sample() picks unique elements (no repeats).

import random

lotto = random.sample(range(1, 50), 6)
print(lotto)

06. Random Numbers with NumPy

numpy.random is great for scientific computing and arrays.

import numpy as np

# Random float array (1D)
arr = np.random.random(5)
print(arr)
# Random integer 2D array
rand_matrix = np.random.randint(1, 100, size=(3, 4))
print(rand_matrix)

07. Comparison Table: Random Number Methods

Method Returns Range Use Case
random.randint(a, b) Integer [a, b] Random whole number
random.random() Float [0.0, 1.0) Probability or unit interval
random.uniform(a, b) Float [a, b] Float range
random.choice(seq) Element Any in sequence Pick from options
np.random.random(size) ndarray [0.0, 1.0) Float array
np.random.randint(low, high, size) ndarray [low, high) Integer array

Conclusion

Python's random module makes generating random values easy and versatile. Use randint() for integers, random() for a float in [0.0, 1.0), and uniform() for any float range. Add numpy when you need fast array-based random number generation for scientific or larger data applications.

Comments