Programs often require the use of random numbers in everything from games to cyber security.
To see random numbers in action, you'll make a virtual board game where the player rolls dice.
Note: It's technically impossible to generate a truly random number with a computer. Because of this, programmers often call random numbers pseudorandom. The first step in generating a random number is importing the random number generator. It's common for a programming language to have extra libraries that need to be imported. Create a new Python file.
Add
import random to the first line.
That's the random library. Now to generate some numbers! When using a random number, it's important to set the range. For example, a Roll the Dice program could roll a 12-sided die, generating a random number between 1 and 12, including the end numbers.
Type a print statement letting the user know that a random number is being generated.
Print:
random.randint(1, 12)Run the program.
Add a new line of code to print a random number between 1 and 100.
import randomThe program will print a random number between 1 and 12. Libraries are collections of premade code you can import and use in your programs. You have to import Python's random library to use it.
print ("Rolling the Dice!")
print (random.randint(1, 12))
print (random.randint(1, 100))
random.randint(x, y) generates a random integer, with x as the minimum and y as the maximum.