Welcome back to our ongoing series on Python’s Standard Library. In case you missed the first part, we covered some of the most commonly used modules like `os`, `sys`, and `math`. But let’s not waste any more time Let’s get started with Part II!
First up, we have a module that I personally use on a daily basis: `random`. This little gem allows us to generate random numbers, shuffle lists, and even pick items from a list at random. It’s perfect for those times when you need to simulate some sort of random behavior in your code.
Here’s an example that demonstrates how to use the `randint()` function:
# Import the random module to access its functions
import random
# Use the randint() function to generate a random integer between 1 and 6 (inclusive)
roll = random.randint(1, 6)
# Print a message to display the result of the random roll
print("You rolled a {}!".format(roll))
This code generates a random integer between `1` and `6`, inclusive. The output might look something like this:
# Import the random module to generate random numbers
import random
# Use the randint() function from the random module to generate a random integer between 1 and 6, inclusive
# Assign the result to the variable "roll"
roll = random.randint(1, 6)
# Print the result of the roll with a string indicating the outcome
print("You rolled a " + str(roll) + "!")
But what if you want to generate multiple rolls at once? You could call the `randint()` function repeatedly, but that would be tedious and inefficient. Instead, we can use a list comprehension to generate an array of random numbers:
# Import the random module
import random
# Generate a list of 10 random numbers between 1 and 6 (inclusive)
rolls = [random.randint(1, 6) for _ in range(10)]
# Print a message to indicate the numbers rolled
print("You rolled the following numbers:")
# Use a for loop to iterate through the list of rolls
for num in rolls:
# Convert each number to a string and print it on a new line
print(str(num))
# The above code can also be written using a list comprehension:
# print("You rolled the following numbers:\n{}".format("\n".join([str(num) for num in rolls])))
# The range function creates a sequence of numbers starting from 0 to 9 (10 numbers in total)
# The underscore (_) is used as a placeholder for the loop variable, as it is not needed in this case
# The randint function generates a random integer between 1 and 6 (inclusive) for each iteration
# The generated numbers are added to the list using the append method
# The list comprehension is a more efficient way of creating a list compared to using a for loop and append method
# The join method joins the list elements with a newline character (\n) to create a string
# The format method is used to insert the string of rolled numbers into the message to be printed
This code generates an array of `10` random integers between `1` and `6`, inclusive. The output might look something like this:
// This code generates an array of 10 random integers between 1 and 6, inclusive.
// The output might look something like this:
// You rolled the following numbers:
// 3
// 5
// 4
// 2
// 6
// 1
// 5
// 4
// 3
// 6
// Create an empty array to store the random numbers
let numbers = [];
// Use a for loop to generate 10 random numbers
for (let i = 0; i < 10; i++) {
// Generate a random number between 1 and 6, inclusive
let randomNumber = Math.floor(Math.random() * 6) + 1;
// Add the random number to the array
numbers.push(randomNumber);
}
// Print a message to the console
console.log("You rolled the following numbers:");
// Use a for loop to iterate through the array and print each number on a new line
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
But what if you want to shuffle a list? You could use a loop and swap elements randomly, but that would be inefficient. Instead, we can use the `shuffle()` function:
# Import the random module to access the shuffle() function
import random
# Create a list of numbers
numbers = [1, 2, 3, 4, 5]
# Use the shuffle() function to randomly rearrange the elements in the list
random.shuffle(numbers)
# Print the shuffled list
print("The shuffled list is: {}".format(numbers))
This code creates an array of `5` numbers and then uses the `shuffle()` function to rearrange them randomly. The output might look something like this:
// Creates an array of 5 numbers
let numbers = [1, 2, 3, 4, 5];
// Uses the shuffle() function to rearrange the numbers randomly
numbers.shuffle();
// Prints the shuffled list
console.log("The shuffled list is: " + numbers);
But what if you want to pick an item from a list at random? You could use the `randint()` function and indexing, but that would be inefficient. Instead, we can use the `choice()` function:
# Import the random module
import random
# Create a list of colors
colors = ["red", "green", "blue"]
# Use the choice() function to select a random color from the list
color = random.choice(colors)
# Print the randomly selected color
print("The randomly selected color is: {}".format(color))
This code creates an array of `3` colors and then uses the `choice()` function to select one at random. The output might look something like this:
// Creates an array of 3 colors
var colors = ["red", "blue", "green"];
// Uses the choice() function to select a random color from the array
var randomColor = choice(colors);
// Prints the randomly selected color to the console
console.log("The randomly selected color is: " + randomColor);
And that’s it for Part II! We covered some of the most commonly used modules in Python’s Standard Library, including `random`. In case you missed any of our previous articles, be sure to check them out. And stay tuned for Part III we’ve got even more exciting modules to cover!
Later!