Developer Tools for Random Data Generation // v2.5.1
root@generate-random:~/numbers/python$ _

Generate Random Numbers in Python

Complete code tutorial with examples and best practices

[ Code Example - Quick Summary ]

Language: Python

What: Generate random numbers in Python using the <code>random</code> module for general purposes or the <code>secrets</code> module for cryptographically secure random numbers.

Try it: Use our interactive Numbers generator or integrate this code into your Python application.

Generate random numbers in Python using the random module for general purposes or the secrets module for cryptographically secure random numbers. Looking for other languages? Check our code examples in PHP , JavaScript , Java , C# , C++ , Ruby and Go or use our interactive web generator.

Python Code Example

import random
import secrets

# Generate a single random number between 1 and 100
random_number = random.randint(1, 100)
print(random_number)  # Example output: 42

# Generate multiple random numbers
numbers = [random.randint(1, 100) for _ in range(10)]
print(numbers)
# Example output: [23, 7, 91, 45, 12, 68, 3, 89, 54, 31]

# Generate cryptographically secure random number
secure_number = secrets.randbelow(100) + 1  # 1 to 100
print(secure_number)  # Example: 67

# Random float between 0 and 100
random_float = random.uniform(0, 100)
print(f"{random_float:.2f}")  # Example: 42.17

# Using NumPy for array generation
import numpy as np
numpy_numbers = np.random.randint(1, 101, size=10)
print(numpy_numbers)
# Example output: [23  7 91 45 12 68  3 89 54 31]

[EXPLANATION]

random.randint(a, b) returns a random integer between a and b (both inclusive). The secrets module provides cryptographically secure random numbers suitable for security-sensitive applications. For large-scale numerical work, use NumPy's numpy.random module.

Expected Output

42
[23, 7, 91, 45, 12, 68, 3, 89, 54, 31]
67
42.17
[23  7 91 45 12 68  3 89 54 31]

Common Use Cases

  • Machine learning data shuffling and train/test splits
  • Monte Carlo simulations and statistical modeling
  • Random sampling for data analysis
  • Game development and procedural generation
  • Cryptographic token generation with secrets module
  • Scientific computing with NumPy arrays

Important Notes

  • Import random module: import random
  • Use secrets for password, token, or key generation
  • NumPy is faster for generating large arrays of random numbers
  • random.seed() sets seed for reproducible results

Try Our Interactive Generator

Don't want to write code? Use our free web-based Numbers generator with instant results.

TRY NUMBERS GENERATOR →