Random Numbers
Producing a random number is useful in many different applications. Computers are unable to produce truly random numbers, but they can make something that looks random. There is a built in module in Python called random that we can use to create random numbers. You need to import the module before you can use it:
- import random
- a = random.randint(0,100)
- print (a)
This will create a random integer between 0 and 100. You could also use this:
- import random
- b = random.randrange(10,50,5)
- print (b)
This creates a random multiple of 5 between 10 and 50. The third digit, the 5, is the step value. This would always produce one of the following: 10, 15, 20, 25, 30, 35, 40, 45, 50
You can also create a random letter. To do so you need to import the string module first:
- import random
- import string
- alphabet = string.ascii_letters
- letter = random.choice(alphabet)
- print (letter)
The string.ascii_letters creates a list containing the alphabet twice, once in lower case and once in upper case. The random.choice() method can be used with a string, a list, a tuple, even a range of numbers.
Note, when importing 2 or more modules you don't have to write import twice, you can use import random, string.