Random numbers¶
Definition¶
Python can create random numbers. These are numbers chosen at random between two numbers and can be either integers or floating point numbers.
Easy example¶
import random
print(random.randint(1,10))
3
Note
This program will produce a random integer between 1 and 10. It is likely to produce a different number the next time it is run.
Syntax¶
import random #This imports the random number library so that we can use it in our program
random.randint(lowNumber, highNumber)
Examples¶
Example 1 - Find a random number between two numbers for a dice roll¶
import random
dice = random.randint(1,6)
print('The dice value is: ' + str(dice))
The dice value is: 2
Example 2 - Find a random floating point number between 0.0 and 1.0¶
import random
randomFloat = random.random()
print(randomFloat)
0.5850151855959205
Note
The output will be a floating point number between 0.0
and 1.0
.
Example 3 - Use a random floating point number to toss a coin¶
import random
randomFloat = random.random()
if randomFloat > 0.5:
print('heads')
else:
print('tails')
heads
Note
Randomly this program will print either heads
or tails
.
Example 4 - A random floating point number between 1 and 100¶
import random
randomFloat = random.random() * 100
print(randomFloat)
11.525934431614193
Example 5 - A random percentage between 1 and 100 to two decimal places¶
import random
randomFloat = random.random() * 100
randomPercent = round(randomFloat, 2)
print(str(randomPercent) + '%')
17.55%
Note
Randomly this will produce a percentage between 0.00% and 100.00%
Example 6 - A random choice from a list of options¶
import random
colors = ['red', 'green', 'yellow', 'blue', 'purple']
randomColor = random.choice(colors)
print(randomColor)
purple
Note
An item from the list will be randomly picked.
Example 7 - Shuffle a list¶
import random
colours = ['red', 'green', 'yellow', 'blue', 'purple']
random.shuffle(colours)
print(colours)
['blue', 'green', 'red', 'purple', 'yellow']
Note
The list will be randomly shuffled.
Key points¶
Warning
The random numbers shown below are not perfectly random, so shouldn’t be used for things like cryptography. But they are perfectly good enough for beginner-level programs and most other uses.