Python Basics: The Random Module
Hey guys! As I mentioned last week, I have just started my journey learning Python. As with any new language it is a little slow going at first, but I have started picking up speed and have really started to fall in love with it. One of the things that was a game changer to me this week was being introduced to the Random module and all of the methods inside it that you can use! Today, I’m going to break down the Random module, show you how to add it to your application, and the most important and commonly used functions within it.
What is Random?
Random is a module in Python that generates pseudo-random numbers for various purposes. It’s been super great for all of the silly CLI games I’ve been building, but also has fabulous uses for real life as well.
Importing Random in your Python file is super simple, and similar to importing React components if that’s something you know how to do. At the top of your Python document, simply type:
That’s it! Now you can call on all of the random functions that your heart desires. Let’s break down a few of them that I love now.
Random Functions To Know
This function is the most commonly used in terms of returning random numbers. The function has two parameters, that are the range, and the function will return a random integer inside that range.
random.randint(1, 10) # returns a number between 1 and 10
This function is great for any sort of application where you need to rely on chance. Rock, Paper, Scissors! Heads or Tails! Roulette! These are all things with an equal amount of probability where you can assign each choice to a number.
This function doesn’t take any parameters, and returns a number between 0.0 and 1.0.
random.random() # 0.3
This is definitely my favorite of the random functions. It takes as its parameter a list, and will choose a random item from that list.
fruits = ["Apple", "Pear", "Banana", "Peach", "Plum"]random.choice(fruits) # "Banana"
random.choice(fruits) # "Plum
This is a way of creating an even simpler game of chance; instead of having to assign each selection to a number, you can create an array of all of the choices like so:
choices = ["Rock", "Paper", "Scissors"]
Another great one for lists, random.shuffle() will take a list and mix it up into a random order. Let’s use the same fruits list from above:
fruits = ["Apple", "Pear", "Banana", "Peach", "Plum"]random.shuffle(fruits) # ["Pear", "Plum", "Apple", "Peach", "Banana"]