Lab 05 Pre Lab

Lists

Lists are an easy way to hold lots of individual pieces of data without needing to make lots of variables. They are a type of data structure, which are specialized ways of organizing and storing data.

Indexing

In order to get a specific variable, or element, from a list, we need to access that index of the list.

For example, the following line of code creates a list called names:

names = ["Aya", "Brad", "Carlos", "David", "Emma"]

Which creates the list (called names) below:

If we then want to access a specific element of the list, we again use the square bracket notation to indicate which index we want to see contents of.

• print( names[0] )           # Print out "Aya"
• print( names[-1] )          # Print out "Emma"
• myVar = 7
• print( names[myVar - 5] )   # Print out "Carlos"

Remember: Lists don't starting counting from 1 — the first element in the list is at index 0.

Mutating lists

Lists can also be "mutated" — we can add and remove items from them as many times as we want. This means that we can start off with an empty list (denoted as two square brackets: emptyList = [] ) and fill it as necessary.

Adding to a list is easy to do: simply add the new item to the end of the list, using the .append() function. The following line of code adds a few items to the list called emptyList:

• emptyList.append("A Thing")
• emptyList.append(1.37)
• emptyList.append(0)
• emptyList.append(False)

After we run these lines of code, our list would look like this:

To remove items from the list, we use the appropriately named .remove() function. The .remove() function takes in what we want to remove, not where it is in the list. For example, if we tell it to remove 0, it will remove the third element, the integer 0, and not the string "A Thing", which is stored at index 0.

• emptyList.remove(0)

The .remove() function also updates the indexes of everything after the removed element, so that our list looks like a regular list after the element was deleted. (In other words, notice how the index at which False is stored changes from 3 before the removal to 2 afterwards.)

While loops

A while loop statement in the Python programming language repeatedly executes a target statement as long as a given Boolean condition is True.

Syntax and use

The syntax of a while loop in the Python programming language is:

• while condition:
•     statement(s)

Here, statement(s) may be a single statement or a block of statements. The condition can be any expression, as long as it evaluates to either True or False. (Remember, any non-zero value is seen as True by Python.) The while loop continues to run as long as the condition is still True. In other words, it runs while the condition is True.

As soon as the condition evaluates to False, program control passes to the line of code immediately following the statements inside the while loop. This is the first line of code after the while loop and its statements. It is indented to the same depth as the "while condition:" line of code.

Remember that in Python, all the statements indented by the same number of character spaces after while (or if, etc.) statements are considered to be part of a single block of code. Python uses indentation as its method of grouping statements.

It is possible that a while loop may not ever run the statement(s) inside the while loop. If the condition is tested and the result is False, the loop body (the statements) will be skipped and the first line of code after the while loop will be executed.

Interactive loops

One of the major uses of a while loop is to interact with the user of the program. Users are unpredictable, and we can't always rely on them to act in the correct way, or to follow the restrictions or directions we give.

Our program may need to ask a user for something over and over and over before it is satisfied. The user may be entering multiple pieces of information, or they may be giving us invalid data (such as a negative score on a quiz, or an email address with no "@" symbol in it). Since we don't know how many times we'll have to reprompt the user, it makes the most sense to use a while loop when interacting with the user in this way.

Input-verification loops

The first type of interactive while loop is one that verifies input from the user. In this case, we continually reject the user's answer until it is satisfactory. The pseudocode for one of these loops might look like this:

• Ask the user for their input
• While the input is not valid:
•     Reprompt the user for new input

In an input-verifying loop, it is very important that you tell the user what is unacceptable about their input, and how to fix it.

Sentinel loops

Another way to use a while loop is as a sentinel loop. A sentinel loop continues to process data until reaching a special value that signals the end. The special value is called the sentinel.

You can choose any value for the sentinel. The only requirement is that it must be distinguishable from actual data values. It is also important that the sentinel is not processed as regular data (e.g., stored at the end of a user-created list, or included in the final calculation).

Here is some pseudocode for a sentinel loop in Python:

• Get the first data item from the user
• While data item is not the sentinel:
•     Process the data item
•     Get the next data item from the user

In a sentinel loop, it is very important that you tell the user what the sentinel value is, so that they can easily exit the loop at any time.

One of the scenarios in which we can implement this type of loop is shown below. In it, we ask the user to tell us some of their favorite things, allowing them to enter as many as they want, until the sentinel value of "NO MORE" is entered.

• def main():
• SENTINEL = "NO MORE"
• faves = []
•
• # Since the input() function doesn't allow commas, we need to
• #   concatenate the sentinel into the user prompt
• # Saving it as a variable means we only have to do it once
• prompt = "What is one of your favorite things? Enter '" + SENTINEL + "' to stop: "
•
• # Use the string variable called "prompt" as what we print to the user
• newFave = input(prompt)
•
• while newFave != SENTINEL:
•     faves.append(newFave)
•     newFave = input(prompt)
•
• # Once the while loop exits, we are done asking about favorite things,
• #   so let's print out the full list to the user, item by item
• # We want to print it out in order, so we print faves[0], then faves[1], etc...
• index = 0
•
• while index < len(faves):
•     print( faves[index] )
•     index = index + 1     # Don't forget to update the loop variable!
•
• # At the end, print out "These are a few of your favorite things"
• print("These are a few of your favorite things")
•
• main()

When the above code is executed, it produces the following result (with user input in blue):

• What is one of your favorite things? Enter 'NO MORE' to stop: Pumpkin spice lattes
• What is one of your favorite things? Enter 'NO MORE' to stop: Good grades on exams
• What is one of your favorite things? Enter 'NO MORE' to stop: Adorable puppies
• What is one of your favorite things? Enter 'NO MORE' to stop: Easy-to-write programs
• What is one of your favorite things? Enter 'NO MORE' to stop: Halloween costumes that require wings
• What is one of your favorite things? Enter 'NO MORE' to stop: NO MORE
•
• Pumpkin spice lattes