1 Always and Forever...
1.1 Raw Input
1.2 Converting string literals into different types
1.3 Indefinite looping
1.4 While statement
1.5 Solve problem
1.6 Look Ahead To Thursday
1.7 Course Changes
1.8 Skills
1.9 Debugging Challenge
1.10 Self Assessment
1.11 Version : 2014/ 02/ 05

CS 110X Feb 04 2014

Lecture Path: 10
Back Next

Expected reading: 233-242
Expected interaction: While vs. For Function Basics Params / return help(), docstrings

Then hate me when thou wilt; if ever, now;
Now, while the world is bent my deeds to cross,
Join with the spite of fortune, make me bow,
And do not drop in for an after-loss:
William Shakespeare

1 Always and Forever...

There are some specific skills that we need to introduce, which have been delayed until after the first exam. Let’s cover those first before beginning the primary discussion of this lesson.

1.1 Raw Input

In all of the examples where you read keyboard input from the user, you were able to use the input(prompt) method, which properly convered the information entered by the user into the appropriate type. You can use input(prompt) for:

But what if you want to simply read in a sequence of characters as input and treat it as a string literal? In this case, you cannot simply use input.

You can retrieve the exact characters typed by the user as text using the raw_input function, as shown below:

>>> s = raw_input("Enter any sequence of characters: ") Enter any sequence of characters: ADK][;salsm >>> s ’ADK][;salsm’

Why would this be useful? For starters, if you wanted the user to simply type in a word like STOP to terminate a program, you can do that instead of having to have them enter in ’STOP’ with quotes. Which would you prefer?

1.2 Converting string literals into different types

Now that you are having the user enter in straight text, you can interpret the text in different ways. You have already seen how to convert integers and floats into strings so you can then concatenate the strings. The reverse operations are also available, namely, to convert string literals into values.

The int(s) function takes a string literal and converts it into an integer.

>>> s = raw_input("Enter an integer: ") Enter an integer: 345 >>> s ’345’ >>> int(s) 345

The string is converted into an integer. Note that as you might expect, you can convert strings into other types as well.

>>> float(’99.8877665544332211’) 99.88776655443323

The int(f) function can also take a floating point value and convert it into an int value. This is useful, for example, when you simply want to truncate the decimals off of a number.

>>> int(99.8877665) 99

1.3 Indefinite looping

Have the user enter in one number at a time; if the user enters the same number twice, then print a warning that the number has already been entered. Once user signals they are done, return the full list of unique values entered.

In all of our examples of looping, we had a definite goal in mind, whether to visit all elements of a list or iterating over integers in a distinct range. There are many times when a program must loop an indefinite number of times, and suddenly stop when a predetermined condition occurs.

This is known as the while loop, and it offers greater flexibility to the programmer.

1.4 While statement

To describe while, let’s start with a simple example:

idx = 0 while idx < 10: print (idx) idx = idx + 1

This loop will execute its body of Python statements as long as a specific condition is true. In this case, the condition is idx < 10. Before the while loop executes for the first time, idx is 0. As you are about to enter the while loop, the condition is checked (0 < 10) and so the loop begins. Each time through the loop, you can see that idx is incremented by 1, thus you know that it will execute 10 times (for 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.

You have to be quite careful with while loops. The following code, for example, loops forever:

idx = 1 while idx > 0: idx = idx + 1

idx will continue to increase with each pass through the loop, and it will never leave the loop, once you’ve entered the loop.

Such "infinite loops" are actually quite necessary and important. Think of the embedded software in your garage door opener that literally is running "forever" waiting for a specific signal to appear, at which time it opens the door.

Of course, if you don’t want to run forever, you need to make sure that at some point, the body of the while loop updates some variable to make sure that the condition becomes invalidated, thus allowing the loop to exit.

1.5 Solve problem

How can you use the while statement to solve the stated problem?

Have the user enter in one number at a time, until the user enters the same number twice. Then return the full list of values entered.

First note that you don’t know in advance how many numbers the users is going to enter. And since the numbers are to be entered one at a time, you can’t rely on inputing the entire list.

So the goal is to use your skill in appending a value to a list. Since the user is going to enter the values one at a time, you can check whether the value is already in the list before adding it. Let’s start with a small example showing how to add up to 10 numbers to a list, without repeating.

def readUniqueValues(): uniqueList = [] for i in range(10): num = input("Enter a number: ") # check to make sure not already in the list. # Add only if not if num in uniqueList: print ("You have already entered that number. ") else: uniqueList.append(num) return (uniqueList)

The following is going to "build up" the uniqueList of values entered by the user, ensuring that the same value doesn’t get inserted more than once. This example, however, still limits the user to (in advance) no more than ten numbers; and if they type a duplicate, they lost that chance to add a number.

The while loop comes to the rescue:

# Read in a set of unique values def readUniqueValues(): uniqueList = [] # Loop forever until we know we are done.. print ("Simply press Enter when done") while True: rawString = raw_input("Enter a number: ") if rawString == ’’: break num = int(rawString) # check to make sure not already in the list. # Add only if not if num in uniqueList: print ("You have already entered that number. ") else: uniqueList.append(num) return (uniqueList)

This code example contains all of the traits you expect to see in a while loop.

1.6 Look Ahead To Thursday

We are going to introduce the next major cognitive building block on Thursday. Whenever I have asked you to write a program you ended up writing a single function. And so, your current understanding of a Python module is that it can contain a number of independent functions; at least, this is what your homework solutions have looked like.

Moving ahead, I am going to show you how (and why!) to develop additional helper functions to be able to write a single program that is divided among multiple interacting functions.

Beginning with Homework 3 you started seeing how you could write functions that could be used by other functions in the same module. We will continue this line of thought on to more complicated solutions.

First I need to explain why this technique is so important. Often you will find that you implement a bit of functionality that can be used by any number of programs. The above code, for example, allows you to read in a set of numbers that are guaranteed to all be unique. This might be a very useful feature for your application domain. For this reason, the function is clearly defined to return a list of unique numbers. such as str(...) and len(...), so this should be recognizable to you.

You might also be intrigued to see that you have, essentially, extended the Python platform. Now, anytime you want to have the user enter in a list of unique values, you can use the following code snippet.

myList = readUniqueValues()

In fact, you can try this right in the Python shell window interpreter. Try it now:

>>> myList = readUniqueValues() Simply press Enter when done Enter a number: 2 Enter a number: 3 Enter a number: 2 You have already entered that number. Enter a number: 3 You have already entered that number. Enter a number: 2 You have already entered that number. Enter a number: 3 You have already entered that number. Enter a number: 2 You have already entered that number. Enter a number: 1 Enter a number: >>> print (myList)

You might also see something interesting in the above code. What is with the first line of the function that starts with three double-quotes?

This is your first exposure to how to properly document a function so the user knows what it does.

If this documentation string is available as the first line of a function definition, then you can see it when you type the function in the Python shell window.

For example, type "readUniqueValues" in a Python Shell window, and then type the open parenthesis "(" and wait. The IDLE editor will provide useful documentation about the function as hovering text. This is the prime way that functions are documented, and you will use this extensively moving forward.

1.7 Course Changes

We have now completed 1/3rd of the course and it is likely that I will make a number of changes to the format and/or delivery. I will list those changes here.

  • TBD

  • TBD

that are similar to the kind you will face on the homework assignment.} )

1.8 Skills

1.9 Debugging Challenge

Working with a while loop can be irritating. Try your hand at the following code, which tries to read a list of values and validate that it represents the permutation of the numbers 1 to n, where n is the length of the list.

Press To Reveal

# read in a list of values and attempt to determine if # it represents a permutation of values 1..n def isPermutation(): myList = input ("Enter list of values [a,b, ..., z]: ") num = len(myList) while num > 0: if not myList.index(num): break if num != 0: print ("Values represent permutation")

Defects

1.10 Self Assessment

Have the user enter in one number at a time, until the user enters the same number twice. Then print out the full list of values entered.

This offers a simplified version of the exercise starting out this lecture. There are two ways to solve it, and I will post both solutions for you to compare notes.

1.11 Version : 2014/02/05

(c) 2014, George Heineman