How to Generate Random Numbers in Python?

Generating random numbers is a common requirement in programming for tasks like simulations, gaming, and security. Python’s random module provides functions to generate random numbers and selections.

Importing the random Module

To use random number functions, first import the module:

import random

Generating Random Integers

Use randint() to generate a random integer between two values:

num = random.randint(1, 10)
print(num)  # Output: Random integer between 1 and 10

Generating Random Floats

Use random() to generate a random float between 0 and 1:

num = random.random()
print(num)  # Output: Random float between 0.0 and 1.0

Random Choice from a List

Select a random element from a list:

choices = ['apple', 'banana', 'cherry']
fruit = random.choice(choices)
print(fruit)

Shuffling a List

Randomly shuffle the elements of a list:

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

Setting a Seed

For reproducible results, set a seed:

random.seed(42)
print(random.randint(1, 10))

Conclusion

Python’s random module is a powerful tool for generating random data. Whether you need random numbers, selections, or shuffling, this module has you covered.

Leave a Reply

Your email address will not be published. Required fields are marked *