115. Python’s random Module

Here are 10 Python code snippets demonstrating how to use Python's random module to generate pseudo-random numbers and perform various random operations.


1. Generating a Random Integer

import random

# Generate a random integer between 1 and 100
random_integer = random.randint(1, 100)
print(f"Random Integer: {random_integer}")

2. Generating a Random Float

import random

# Generate a random float between 0 and 1
random_float = random.random()
print(f"Random Float: {random_float}")

3. Selecting a Random Item from a List

import random

# Randomly select an item from a list
choices = ['apple', 'banana', 'cherry', 'date']
random_item = random.choice(choices)
print(f"Random Choice: {random_item}")

4. Selecting Multiple Random Items


5. Shuffling a List


6. Generating a Random Range


7. Generating Random Numbers with a Normal Distribution


8. Generating a Random Boolean


9. Generating a Random String


10. Generating Reproducible Random Results


Summary:

The random module provides tools for:

  • Generating random numbers (randint, random, randrange).

  • Random selection (choice, sample).

  • Shuffling (shuffle).

  • Advanced distributions (e.g., gauss).

  • Creating reproducible random results using seed.

Let me know if you'd like detailed explanations for any of these functions!

Last updated