Implementing our algorithm in Python to generate data
We are going to use Python to implement the algorithm we wrote:
Import a random number generator.
Create an empty list, one with no elements (pieces of data) in it.
Ask the user how many elements they want in their list
For each position in the list:
generate a random number and add it on the end of the existing list
for each position in the list:
print out what is in that position
Q1. Type this code in and get it working:
Q2. Generate lists of size 7, 10, 20, 50 and 1000.
Q3. Repeat Q2 but change the code so you only generate numbers between 1 and 10 inclusive. Check your results very carefully and make sure that your code does generate all the numbers required and it doesn't generate numbers outside this range!
The for loop in the lines:
for i in range(size): # for i= 0 to (size-1)
myArray.append(random.randint(1,500)) # get a random number and append it
is very common in Python so we should make sure we understand it. Firstly, range(size) generates numbers starting at 0 and up to but not including whatever 'size' is. For example,
range(5) generates 0, 1, 2, 3 and 4
range(7) generates 0, 1, 2, 3, 4, 5, 6
For loops are used to repeat code. We want to repeat this line:
myArray.append(random.randint(1,500))
'size' number of times.
If size is 6, we want to repeat myArray.append(random.randint(1,500)) six times. We count each time we do the code, but starting at 0.
So the first time we do the code, i = 0. We then do the code.
Then we loop back, i = 1, and we do the code again.
Then we loop back, i = 2, and we do the code again.
Then we loop back, i = 3, and we do the code again.
Then we loop back, i = 4, and we do the code again.
Then we loop back, i = 5, and we do the code again and finish.
We have done the code six times, but we just started counting at 0 instead of 1. Programmers always like to count from 0, for some very good reasons, which we won't docuss at the moment. You don't have to use the variable i as the variable counter, by the way. You could have used g, of fish, or parrots, or counter or almost anything! Just remember that it always changes each time we do the loop, and that it starts at 0. we can make use of this variable in our code.
Q4. Explain how i is used in these lines:
for i in range(size): # for i= 0 to (size-1)
print(myArray[i],end=' ') # print what you find at that position
So a for loop lets us do the same code lots of times, but we only have to write one line of code to do it.