In this section, we explore the Python `random` library, a built-in module that allows you to generate pseudo-random numbers for various probabilistic distributions and random selections. Learn how to leverage randomness for simulations, testing, and moreāall through Python code.
Since the `random` library is part of Python's standard library, there's no need to install it separately. You can start using it directly in your code. Here are some examples of how to use the `random` library.
# Import the random library
import random
# Generate a random integer from 1 to 10
random_int = random.randint(1, 10)
print(random_int)
# Generate a random float between 0 and 1
random_float = random.random()
print(random_float)
# Choose a random element from a list
items = ['apple', 'banana', 'cherry']
random_choice = random.choice(items)
print(random_choice)
These basic functions are just the beginning. The `random` library provides a rich set of tools to control randomness, including functions like `shuffle`, `seed`, and more, which you can use to create simulations or games.
Here are some use cases of therandom
library:
random.seed
Do not use the random library for the following: