05. While Loop 1

While Loop 1

Start Quiz:

# Let's learn a little bit of Data Analysis and how we can use
# loops and lists to create, aggregate, and summarize data

# For the part 1, we'll learn a basic way of creating data using
# Python's random number generator.

# To create a random integer from 0 to 10, we first import the 
# "random" module

import random

# We then print a random integer using the random.randint(start, end) function
print "Random number generated: " + str(random.randint(0,10))

# Remember that if we want to concatenate a string and a number, we need to convert the 
# integer into a string using the str() function

# We now want to create a list filled with random numbers. The list should be 
# of length 20

random_list = []
list_length = 20

# Write code here and use a while loop to populate this list of random integers. A crucial
# function that will help you is to use the append() method to add elements to a list.



# When we print this list, we should get a list of random integers such as:
# [7, 5, 1, 6, 4, 1, 0, 6, 6, 8, 1, 1, 2, 7, 5, 10, 7, 8, 1, 3]
print random_list
Solution:

Breaking Down the Problem

We first need to understand what are the inputs and what are the outputs (or results) that we want to obtain.

The inputs are:

  • An empty list
  • A variable that has the value 20, telling us that we want to create a list of length 20

The output is:

  • A list of random integers between 0 and 10 that could look like:

[7, 5, 1, 6, 4, 1, 0, 6, 6, 8, 1, 1, 2, 7, 5, 10, 7, 8, 1, 3]

What To Do

Therefore we want to generate a list of random integers given an empty list. One way is to use the append() method for lists and add in a random integer, 20 times.

That's how a person would do it manually on pen and paper anyway. Let's see if we can write an outline of what to do if we were to do this manually on pen and paper:

  1. Generate a random integer between 0 and 10
  2. Add this random integer to our list
  3. Do we have a list of length 20 yet?
  4. If not, we loop back up and go through steps 1 to 3 again **while** length of the list is less than 20

If we translate these steps into real code, we can use a while loop that checks whether the length of the list is less than 20.

Answer Code

import random

random_list = []
list_length = 20

while len(random_list) < list_length:
   random_list.append(random.randint(0,10))

Here's alternative code that simplifies the logic a bit if the above code is complicated to understand.
import random

random_list = []
list_length = 20
count = 0

while count < list_length:
   random_list.append(random.randint(0,10))
   count += 1