We can generate random numbers in our programs.
In Python, we can do it. But we need to import a library file to help us do this:
import random
Now we can create a random number and assign it to a variable:
x = random.randint(1,10)
print(x)
randint() is a function in the random library file. A you can see, if we give it 2 arguments, it will return a random number.
Random numbers are great for computer games. Here is a simple example. A player has three chances to roll a 6 and win!
Here is a flowchart representing the game algorithm.
The program sets a count to 1. It gets a random number. If the number is not 6 and the count is less than or equal to 3, another random number is generated and the count is incremented.
Here is the pseudocode for the program. Can you fill in the blanks?
count ← 1
roll ← RAND(1,6)
WHILE count<=3 AND roll <> 6 DO
count ← count + 1
roll ← RAND(1,6)
END WHILE
IF count = 6 THEN
OUTPUT roll, ": you win!"
ELSE
OUTPUT count, ": you lose!"
If you are a beginner programmer, this is quite tricky!
Code this in Python to see it working.
iterateauto-indent variablecompile sum machine code count-controlled loop integer pseudocodesyntax