COMP 200 Elements of Computer Science &
COMP 130 Elements of Algorithms and Computation
Spring 2012

Practice with Python Control Flow

Control flow is a general term for the order in which a computer program executes its statements. The “normal” control flow is to use the first line of code, then the second, then the third, etc., in sequence. But, we've now seen several ways to modify this simple sequence. For example, a loop will generally repeat its loop body, and an if will use only one of its conditional branches. It also includes the idea of calling a function, then the program will transfer control to the function body and eventually return.

In short, we're going to practice writing functions that use conditionals or loops. For each of the following problems, read the problem description and examples, define a function to solve the problem, then check your result against our sample solution.

At the end of each semester, instructors have to assign letter grades. For example, a score of 90 or above is an A, 80 or above is a B, 70 or above is a C, 60 or above is a D, and anything else is an F. Define a function letterGrade that takes a score and returns the letter grade as a string.

At the beginning of the semester, we counted how many students had Apple laptops, Windows laptops, or no laptop. Define a function countLaptops that is given a list such as ["Apple", "Apple", "Windows", "none", "Windows", "Apple"]. The function should return three values: how many Apple computers there are, how many Windows computers there are, and how many people don't have a computer.

As a prelude to the next exercise, here's several more examples of using Python strings that you should type in.

See also the Python documentation on string operations.

Some computer software is not able to handle people's names that contain unexpected characters. Define a function validateString that takes two arguments: a string representing a name, and a string that includes all the characters to be considered valid. It returns a Boolean indicating whether all the letters are valid.

Here, we show three possible solutions:

In statistics, a common misunderstanding is to believe that half of a list of numbers are greater than their mean. Actually, that characterizes the median. To illustrate the truth, define a function fractionAboveMean that takes a non-empty list of numbers and returns the fraction that are above the list's mean. For example, fractionAboveMean([3,8,1,9,2]) should return 0.4. Of course, you should use the function arithmeticMean from your first assignment.

The previous class outlined how to quit generating population data when the data became too extreme. Make this change and verify that it works.