Back

Introduction to random numbers

You often need to generate random numbers in your programs, or to get a random string from a list of strings, for example. Python comes with a module to help you easily do these kinds of tasks. It's called random and it comes with many different methods which you can use. You have to always import random into your program before you can use it. you do this using the import keyword at the beginning of your code. You can find information on all of the methods available in the random module in the Python documentation. Simply search for searching for Python random module.

Q1. Get the following code working:

import random

myRandom1=random.random()
print(myRandom1)

Q2. Run the code a few times. You could even put it inside a for loop and run it 100 times automatically:

import random

for number in range(100):
    myRandom1=random.random()
    print(myRandom1)

Describe what this code does.

Q3. Get this code working:

import random

for number in range(100):
    myRandom1=random.uniform(95.0, 110.0)
    print(myRandom1)

Q4. Describe what this code does.
Q5. Get this code working:

import random

for number in range(100):
    myRandom = random.randint(1,100)
    print(myRandom)

Q6. This function produces a number from and including the first number up to but not including the last number. If you wanted to produce a range from 1 - 100 inclusive of 100, how could you do this? Modify your code and check that it works.
Q7. Change the function so that it produces integers in the range of 50 - 70 inclusive.
Q8. Find the Python documentation to do with the Random module. Skim down and read what it says about the randint() method and the randrange() method.
Q9. Write some code to produce an even number from 2 to 100 inclusive. Test it.
Q10. Write some code to produce a random number between 100 and 200 that is divisible by 5.

Back