• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Random / How to Use the Random Module in Python

How to Use the Random Module in Python

Author: PFB Staff Writer
Last Updated: December 28, 2022

In this post, I will describe the use of the random module in Python. The random module provides access to functions that support many operations. Perhaps the most important thing is that it allows you to generate random numbers.

Table of Contents
  1. When to Use the Random Module in Python?
  2. Random Functions in Python
    1. The randint() Function in Python
    2. The random() Function
    3. The choice() Function
    4. The shuffle() Function
    5. The randrange() Function
  3. Code Example For Random Module in Python
  4. Conclusion

When to Use the Random Module in Python?

If you want the computer to pick a random number in a given range, pick a random element from a python list, pick a random card from a deck, flip a coin, etc, you can use the random module in python. You can also use the random module to create random strings while choosing passwords to make your password database more secure or power a random page feature of your website.

Random Functions in Python

The Random module contains some very useful functions namely randint() function, random() function, choice() function, randrange() function and shuffle() function. Let us discuss each of these functions one by one.

The randint() Function in Python

The randint() function which is defined in the python random module can be used to create random strings within a range. The function takes two numbers as its input argument. The first input argument is the start of the range and the second input argument is the end of the range. After execution, the randint() function returns a random integer within the given range.

If we wanted a random integer, we can use the randint() function. For instance, you can generate random integers between 1 and 5 as shown in the following example.

import random
print random.randint(0, 5)

The above code will output either 1, 2, 3, 4, or 5. Here, you should make sure that the first input argument in the randint() function should be less than the second input argument. Otherwise, the program runs into an error.

The random() Function

The random() function in the python random module is used to generate random numbers between 0 and 1. When executed, the random() function returns a floating point number between 0 and 1.

If you want a larger number, you can multiply it by a larger value. For example, to create a random number between 0 and 100, you can multiply the output of the random() function by 100 as shown below.

import random
random.random() * 100

The choice() Function

The choice() function is used to select a random element from a collection object like a list, set, tuple, etc. The function takes a collection object as its input argument and returns a random element.

For example, you can select a random color from a list of colors by passing the list of color names to the choice() function as input as shown in the following example.

random.choice( ['red', 'black', 'green'] ).

The choice function can often be used for choosing a random element from a list.

import random
myList = [2, 109, False, 10, "Lorem", 482, "Ipsum"]
random.choice(myList)

The shuffle() Function

As the name suggests, the shuffle function shuffles the elements in the list in place. The shuffle() function takes a list as an input argument. After execution, the elements of the list are shuffled in a random order as shown in the following example.

from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)
Output:
# print x  gives  [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
# of course your results will vary

The randrange() Function

The randrange() function in the python random module is used to select a random element from a given range. It takes three numbers namely start, stop, and step as input argument. After execution, it generates a randomly selected element from the range(start, stop, step). To understand the working of range() function, you can read this article on python range.

random.randrange(start, stop[, step])
import random
for i in range(3):
    print random.randrange(0, 101, 5)

Effectively, the randrange() function works as a combination of the choice() function and the range() function.

Code Example For Random Module in Python

The following code example uses the choice() function to count the number of heads and tails in 10000 flips of a coin. For this, we define a dictionary named outcomes to store the number of heads and tails. Next, we use the keys() method of the python dictionary to get the list [“heads”, “tails”]. After this, we use the choice() function to select one of the values from the list randomly and update the outcomes dictionary according to the output.

import random
import itertools

outcomes = { 'heads':0,
             'tails':0,
             }
sides = outcomes.keys()

for i in range(10000):
    outcomes[ random.choice(sides) ] += 1

print 'Heads:', outcomes['heads']
print 'Tails:', outcomes['tails']

There are only two outcomes allowed, so rather than use numbers and convert them, the words “heads” and “tails” are used with choice().

The results are tabulated in a dictionary using the outcome names as keys.

$ python random_choice.py

Heads: 4984
Tails: 5016

Conclusion

In this article, we have discussed different functions in the random module in Python. We have also discussed a code example using the choice() function to simulate coin flips.

To learn more about python programming, you can read this article on list comprehension in Python. You might also like this article on string manipulation.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Random Author: PFB Staff Writer

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Select Specific Columns in Pandas Dataframe
  • Convert Epoch to Datetime in Python
  • Iterate Rows in a Pandas Dataframe
  • Split String Into Characters in Python
  • Pandas Map Function to Series in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us