Learn
Modules: Python
Modules Python Random

datetime is just the beginning. There are hundreds of Python modules that you can use. Another one of the most commonly used is random which allows you to generate numbers or select items at random.

With random, we’ll be using more than one piece of the module’s functionality, so the import syntax will look like:

import random

We’ll work with two common random functions:

  • random.choice() which takes a list as an argument and returns a number from the list
  • random.randint() which takes two numbers as arguments and generates a random number between the two numbers you passed in

Let’s take randomness to a whole new level by picking a random number from a list of randomly generated numbers between 1 and 100.

Instructions

1.

In script.py import the random library.

2.

Create a variable random_list and set it equal to an empty list

3.

Turn the empty list into a list comprehension that uses random.randint() to generate a random integer between 1 and 100 (inclusive) for each number in range(101).

4.

Create a new variable randomer_number and set it equal to random.choice() with random_list as an argument.

5.

Print randomer_number out to see what number was picked!

Folder Icon

Sign up to start coding

Already have an account?