- What is the random module
- How to generate random numbers
- How to select random items
- What is the pseudorandom
Python is famous for having many standard libraries, called modules and packages, with thousands of different functions implemented. It's useful for developers to understand these standard libraries, as this knowledge saves time and effort.
In this lesson, we'll get acquainted with one of the standard libraries, the random
module.
What is the random
module
When developing programs, you sometimes need to generate random numbers. You can use the random module in Python for this purpose. It provides many functions, but we'll focus on two for now:
randint
generate an integer within a given rangechoice
select a random item from the given set
How to generate random numbers
To generate a random number, you need to import the randint
function from the random
module:
from random import randint
For example, let's try generating a number from 1 to 100:
random_number = randint(1, 100)
Note that both range boundaries are enabled, so randint
can output any value in the range, including 1 and 100.
Let's move on to a more complex example:
string = 'abcde'
random_index = randint(0, len(string) - 1)
char = string[random_index]
Here, the program selects a random character from the string
. That said:
- The string in the
string
variable has a length of 5 - The index of the last element in the line is 4
- String characters are indexed from zero
If we try to generate a number via randint(0, 5)
, we will get the value 5. Then the program will generate an IndexError
: it won't be able to output the fifth character out of the four.
How do you prevent this? You shouldn't just set the upper limit of the range, but calculate it, i.e., subtract one from the length of the string. It is what we did in the example code above.
How to select random items
Above, we looked at an example in which we chose a random string character. This task arises quite often, so there's a function called choice
in the random
module.
If you use this function, selecting a character from the string will look like this:
from random import choice
string = 'abcde'
char = choice(string)
Using choice
, you won't have to think about range boundaries; the function selects items correctly. It is essential to check that the string in question isn't empty. Otherwise, we get the error IndexError: Cannot choose from an empty sequence
.
What is the pseudorandom
The random
module is based on a pseudorandom number generator. The algorithm chooses numbers not randomly but based on complex mathematical calculations. Because of this, we shouldn't use it in situations requiring increased security.
Cryptography, encryption, and other similar applications use the secrets module, based on a less predictable random generation mechanism.