Introduction to random numbers - Answers
Q1. Get the following code working:
import random
myRandom1=random.random()
print(myRandom1)
Q2. This code imports the random module. It then generates a random floating point number between 0.0 and 1.0 and prints it out. By putting the code in a for loop, you can run the random number generator lots of times automatically, to see if it looks like it is working correctly.
Q3. Get this code working:
import random
for number in range(100):
myRandom1=random.uniform(95.0, 110.0)
print(myRandom1)
Q4. This code generates a random floating point number between 95.0 and 110.0 and then prints it out. It does this 100 times.
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, you could change the upper limit of the range to 101.
Q7. To change the function so that it produces integers in the range of 50 - 70 inclusive, do this:
import random
for number in range(100):
myRandom = random.randint(50,71)
print(myRandom)
Q8. Read the Python documentation to do with the random module.
Q9. To generate a random even number from 2 to 100 inclusive, do this:
import random
for number in range(200):
myRandom = random.randrange(2,102,2)
print(myRandom)
Q10. To generate a random number between 100 and 200 divisible by 5.
for number in range(200):
myRandom = random.randrange(100,201,5)
print(myRandom)