To use Random
To use the random command we must first import the random section from Python’s code library on the first line of the program:
Generate a Random Number
To generate a random number you need to use the random.randint command (randint stands for random integer). After this command, in brackets declare the range of numbers to choose from, e.g. (1,20) or (100,1000). Like an input line, you also need to save this random number into a variable such as below:
Above is a valid random number generation line but it needs the import command and a print line to be a complete program:
Below are three different instances of this program when run:
The two values in the brackets of a random.randint command denote the upper and lower limits of the random selection. They do not have to be fixed values however and could be replaced by variables. Below is a program where the user selects the upper and lower values of the range:
Below are two different examples of the program when run:
Generating Random Characters
Rather than just numbers, we can also randomly generate different characters from a specified range by using the command: random.choice. Just like before, you need to specify the range to select from in brackets after the command.
Below is a program that randomly chooses a letter of the alphabet:
And below are three different outcomes for this program:
Of course, the range of characters to choose from does not have to be solely letters, you could use numbers or punctuation. Also, the range does not have to be fixed either, you could allow the user to enter data as a variable and select from that instead, such as below:
Below are three different outcomes with three different inputted entries:
Generating a Random Sample
The code in the previous two sections is fine if you want to randomly select just a single value but if you wished to generate more than one entity then you could use a for loop to do so:
The above code, run three times could give the following output:
Alternately, to choose more than one value from a set of data you could use the command: random.sample. After you have written this command you need to specify the list of values to sample from and how many values you want to choose:
Be careful with your brackets. The string values but be within speech marks and separated by commas and enclosed within square brackets. After the list of string values you need another comma and then a value to denote how many values to select.
Below is a program that selects three values from a list of strings and outputs them, remember to include import random at the start for every program using a random command.
Two examples of this program being run are as follows:
You can also use the random.sample command to choose several integers from a given range. By implementing the range command too, you don’t need to individually write out each value like the string example above.
Three different outcomes of this code are as follows: