How to generate random numbers in Python Pro Preview

When installing Python, a number of widely used libraries are also installed alongside it. One such library is the "random" library. This library allows us to generate random numbers in between a range defined by us.

At every start of the program, they will be different, but sometimes they will match. They are random after all!

To access the full video please subscribe to FLLCasts.com

Subscribe

  • #1556
  • 06 Mar 2020

In order to use this library, we must import it first. For this purpose, you must add the following line to the beginning of your program:

import random

Now we can use the commands in this library!

In order to generate a random number, we can use the random.randint() command. This command has two input parameters:

  1. The smallest number it can select;
  2. The largest number it can select.

Here's an example where we write a random number between 0 and 10 in a variable named "secret_number":

secret_number = random.randint(0, 10)

If you wish to learn more about how these random numbers are generated, you can follow this linkThere you will find a detailed explanation on how the random library works.

Courses and lessons with this Tutorial

This Tutorial is used in the following courses and lessons

Image for Python with LEGO Mindstorms EV3 - Level 1
  • 74
  • 28:18
  • 114