Now now now. I have been doing topics on how to use modules and some random stuff. I actually felt like I should not dive into the basics of the random module since you can learn it pretty easily but I just feel like someone, atleast 1 person, still does not understand how it works.
To use the random
library in Python, you usually start by importing it using the import
keyword like this:
import random
Once you’ve imported the random
library, you can use its various functions to generate random numbers, shuffle sequences, and make random choices.
Here’s an example of how to use the random
library to generate a random number between 1 and 10:
import random
random_number = random.randint(1, 10)
print(random_number)
This will output a random number between 1 and 10 (inclusive). You can use other functions like random.choice()
to make random choices from a list, and random.shuffle()
to shuffle the elements of a list in a random order.
Here’s how you can use random.shuffle
and random.choice
to work with a list of fruits:
import random
fruits = ["apple", "banana", "cherry", "kiwi", "orange", "pear"]
random.shuffle(fruits)
print(fruits) # Output: ['kiwi', 'cherry', 'banana', 'pear', 'orange', 'apple']
random_fruit = random.choice(fruits)
print(random_fruit) # Output: e.g. 'pear'
random.shuffle
takes a sequence (a list in this case) and reorders its elements randomly. In the above code, fruits
is shuffled in place. After shuffling, the order of the elements in fruits
is randomized.
random.choice
takes a sequence and returns a random element from it. In the above code, random_fruit
is assigned a value that is a random element of fruits
.
Note that random.shuffle
shuffles a sequence in place, which means that the original list is modified. If you want to shuffle a copy of the list instead, you can make a copy first:
import random
fruits = ["apple", "banana", "cherry", "kiwi", "orange", "pear"]
shuffled_fruits = fruits.copy()
random.shuffle(shuffled_fruits)
print(fruits) # Output: ['apple', 'banana', 'cherry', 'kiwi', 'orange', 'pear']
print(shuffled_fruits) # Output: e.g. ['pear', 'cherry', 'kiwi', 'banana', 'orange', 'apple']
In this code, the copy
method is used to create a separate copy of the fruits
list, which can be shuffled independently of the original.
That is the basics on how to use the random module
I wrote this thing at 2:36 am, slight correction: 2:37 am
yes hope you enjoy good night