Chapter 4. Control Flow

CONTENTS
  •  The if Statement
  •  The while Statement
  •  The for Statement
  •  Putting It All Together
  •  Summary

Terms in This Chapter

  • Argument

  • break and continue statements

  • Built-in (intrinsic) functions

  • Compound statement

  • else/elif clause

  • for loop

  • Function

  • if, for, and while statements

  • Iteration

  • Key/value pair

  • Looping

  • Method

  • Modulus operator

  • Nested dictionary

  • Sequence

  • String format operator

  • Subordinate statement

  • Suite

Control flow instructs Python, on the basis of certain conditions, to execute particular statements and not others. It also allows repeated execution of statements until some conditions are met and permits branching of conditional execution. In this chapter, we'll cover the if, while, and for compound statements, all of which control statement execution in Python.

The if Statement

The if statement conditionally executes a statement's suite. One form is shown here:

if(expression):        suite

Python has to determine whether if's expression is true or false. If the expression is true, Python executes the suite; if not, it doesn't. As we discussed in Chapter 3, Python doesn't have a Boolean (true/false) type. Instead, it uses any numeric value other than zero to indicate true and uses zero, any empty sequence, and the value None to indicate false. For example, the following will print "hello" because the expression contains a value of 1.

>>> # 1 is true >>> if(1): ...     print("hello") ... hello

Notice that the subordinate statement, print, is indented, which shows that it's part of the suite associated with if. In interactive mode, you indent an if suite with the Tab key. The ... prompt indicates a subordinate statement.

The next four statements further illustrate how Python determines whether or not to execute an if statement based on the value in the expression.

>>> #0 is an integer and 0 means false >>> if (0): ...     print("goodbye") ... >>> #3.3 is a float and not equal to 0 so it is true >>> if (3.3): ...     print("hello") ... hello >>> #0.00 is equal to 0, which means false >>> if (0.000): ...     print("goodbye") ... >>> if(0.000000000000000000001): ...     print("hello") ... hello

if can determine if a list is empty, as seen in the checkSeq() function shown in the first example below. The result is shown in the second example. Remember, an empty list indicates false.

>>> def checkSeq(seq): ...     if (seq): ...             print "has item" ...     else : ...             print "empty" ... >>> non_empty_list = [1,2,3] >>> empty_list = [] >>> checkSeq(empty_list) empty >>> checkSeq(non_empty_list) has item

Typically, if statements contain expressions that use comparison and logical operators. To illustrate, let's say that a woman is looking for her perfect man tall, dark, and handsome; the strong, quiet type between the ages of 27 and 35. In Python, she can express her preferences like this:

if (tall and dark and handsome and not talksAlot and (age>27) and (age<35)): #(same line) print ("Hi handsome")

Here's an interactive session that uses the above information to help our female friend meet the man of her dreams:

>>> tall = 1 >>> dark = 1 >>> handsome = 1 >>> talksAlot = 0 >>> age = 32 >>> if (tall and dark and handsome and not talksAlot and (age>27) and (age<35)): ...     print("Hi handsome") ... Hi handsome

At the beginning of the chapter, we saw the basic form of if. We will look at two other forms, containing else and elif clauses, respectively, in the two sections that follow.

else

The else form appears as

if(expression):        suite 1 else:        suite 2

Before it can execute this expression, Python must determine, as usual, whether it's true. If so, Python executes the first suite; if not ("else"), it executes the second suite. The following simple greet() function illustrates the if:else form:

>>> def greet(name, sex): ...              #if female print Ms. ...     if(sex == "female"): ...             print ("Hello Ms. " + name) ...              #if male print Mr. ...     else: ...             print("Hello Mr. " + name) ... >>>    # greet James who is a male >>> greet("James Agular", "male") Hello Mr. James Agular >>>    # greet Jane who is a female >>> greet("Jane Doe", "female") Hello Ms. Jane Doe

We can see that the expression sex == "female" is false, which means that the first time we invoke greet() Python will execute the second suite and print ("Hello Mr. " + name"). However, the second time we invoke greet(), the expression sex = = "female" is true, so Python executes the first suite.

Separating Suites

These two if statements illustrate the two styles of separating suites semicolons and indenting:

>>> sex = "female" >>> name = "Fran Dresser" >>> #First if statement >>> if (sex == "female"):print("Hello,"); print("It's good to see you Ms." + name) ... Hello, It's good to see you Ms.Fran Dresser >>> #second if statement >>> if (sex == "female"): ...     print("Hello,") ...     print ("It's good to see you Ms. " + name) ... Hello, It's good to see you Ms. Fran Dresser

elif

The elif ("else-if") clause appears as

if(expression 1):        suite 1 elif(expression 2):        suite 2 else:        suite 3

which Python translates as "If the expression is true, execute the corresponding suite; else, if the next expression is true, execute the corresponding suite," and so on. The else clause here is actually optional.

Here's an example of elif based on the previous interactive greet() session:

>>> def greet(name, sex): ...     if( sex == "female"): ...             print("Hello Ms. " + name) ...     elif( sex == "male"): ...             print ("Hello Mr. " + name) ...     elif( sex == "undeclared"): ...             print("Hello " + name) ...     else: ...             print("Hello " + name) ...

As you can see from the added clauses, there can be multiple elifs in an if statement. However, the if clause stays the same and uses the same expression. The second clause, ...elif (sex = = "male"):, checks to see if the sex is male and, if so, prints out "Hello Mr". The third clause, ...elif(sex == "undeclared"):, checks to see if the sex has even been declared; if not, it prints a simple "Hello".

So, if we invoke the greet() function like this, the second suite, associated with the first elif clause, is executed:

>>> greet("Bob Dole", "male") Hello Mr. Bob Dole

But if we invoke it like this, the first suite, associated with the if clause, is executed:

>>> greet("Jane Smith", "female") Hello Ms. Jane Smith

Similarly, if we invoke the greet() function like this, the third suite, associated with the second elif clause, is executed:

>>> greet("Jean Costello", "undeclared") Hello Jean Costello

However, if we invoke it like this, the else clause's suite is executed:

>>> greet("Jean Smith", "") Hello Jean Smith

Notice that else is the default, which means that its suite is executed if none of the other clauses' expressions turn out to be true.

To sum up, the if statement is used for conditional execution of suites. As a compound statement, it consists of the if, elif, and else clauses, each of which has an associated suite. By evaluating the expression in each clause until one is found to be true, Python determines which clause's suite to execute. As soon as it finds the right one, it stops evaluating. If all of the expressions are found to be false, Python executes the else clause's suite. If else isn't there and all other clause's expressions are false, no suite is executed.

The while Statement

The while statement repetitively executes a suite until a condition is met. Its basic form is

while( expression ):       suite

which you can think of in English as "While the expression remains true, execute the suite repeatedly." Python carries out this instruction by returning to the top of the statement to check if the expression is still true; if so, it executes the suite a second time and once again returns to the top (this is referred to as looping), repeating this process until the expression becomes false. Once that happens, Python stops executing, and the while statement's execution comes to a halt.

One use of the while statement is to remove items from a list for example, every occurrence of the string cat from the list pets.

>>> pets = ["cat", "dog", "bird", "fish", "cat", "cat", "cat"] #same line

We know from Chapter 2 that a list has a count() method that returns the count of an item in the list and a remove() method that removes the first occurrence of an item. Our goal is to remove the cat string from the pet list while its count is greater than zero. We express this in Python as

>>> pets = ["cat","dog", "bird", "fish", "cat", "cat", "cat"] #same line >>> while(pets.count("cat") > 0): ...     pets.remove("cat") ...     print (pets) ...

To demonstrate what happens at each iteration of the loop, we print each iteration's resulting pets list to get the following output:

['dog', 'bird', 'fish', 'cat', 'cat', 'cat'] ['dog', 'bird', 'fish', 'cat', 'cat'] ['dog', 'bird', 'fish', 'cat']

The first cat was removed on the first execution of the while statement, but there are still three occurrences of cat remaining, so the while loop's suite is executed three more times.

break

The break statement allows you to break out of a while statement before it loops back to the top. This is useful, for example, when inputting several name/phone-number pairs in an address book application. The following statement uses the raw_input() built-in function (which reads a line from the console). An empty string indicates that inputting is complete:

>>> while(1): ...     name = raw_input("Enter in the name: ") ...     if(name == ""): ...             break ...     phone_number = raw_input("Enter in the phone number: ") ...     #Do something useful with the name and phone_number

Notice the while(1): expression, which in effect tells Python to loop the suite forever. However, the break statement stops this "infinite looping" by instructing Python to break out of the loop if it hits an empty name string. Here's the interactive session, followed by its output:

...     if(name == ""): ...             break Enter in the name: Rick Hightower Enter in the phone number: 555-5555 Enter in the name: Adam Carr Enter in the phone number: 555-6666 Enter in the name: >>>

As you can see, the last time we're asked to enter a name, we hit Enter so that the string returned from raw_input is empty.

continue

The continue statement is similar to the break statement. However, instead of instructing Python to break out, it tells it to return to the top of the while statement, that is, where the expression is evaluated. We'll stick with the address book example to illustrate continue, adding the ability to enter an address. If the first line of the address is empty, we can assume that the user doesn't want to exercise this option, and we go back to the top of the loop.

>>> while (1): ...     name = raw_input("Enter in the name: ") ...     if (name == ""): ...             break ...     phone_number = raw_input("Enter in the phone number: ") ...     address_line1 = raw_input("Enter address line one: ") ...     if (address_line1 == ""): ...             continue ...     address_line2 = raw_input("Enter address line two: ") ...     address_line3 = raw_input("Enter address line three: ") ...     #Do something useful with the data we just collected ...

As with break, while(1) triggers an infinite loop of the associated suite. Again, the only way to end the loop is via the break statement.

Since we've added the address option, we test to see if address_line1 is empty. If so, we continue with the next entry, that is, the next iteration of the loop, by adding the following statement:

...     address_line1 = raw_input("Enter address line one: ") ...     if (address_line1 == ""): ...             continue

In English, this says, "Get the first line of a person's address from the user and test to see if it's an empty string. If so, continue executing at the top of the while statement; in other words, get the next person's information."

Below are samples of the output, in order, from the four iterations of the preceding name/phone-number program.

Enter in the name: Rick Hightower Enter in the phone number: 555-5555 Enter address line one: 123 Main St. Enter address line two: Tucson, Az Enter address line three: 85226 Enter in the name: Adam Carr Enter in the phone number: 555-6666 Enter address line one: Enter in the name: Bob Ninny Enter in the phone number: 555-7777 Enter address line one: 1234 South Dobson Enter address line two: Mesa, AZ Enter address line three: 85228 Enter in the name:

In the first iteration, we fill in all fields for Rick Hightower, including the optional address fields. In the second, we fill in only Adam Carr's name and phone number, and at the first address field, hit Enter. The statement below instructs Python to return to the top of the while statement to begin executing again, thus skipping the rest of the statements in while's suite:

...     if (address_line1 == ""): ...             continue

In the third iteration, all of Bob Ninny's fields are filled in. In the fourth iteration, when the program asks us to enter a name, we hit Enter, causing raw_input() to return an empty string. This means that the following statement forces the while loop to terminate:

...     if(name == ""): ...             break

else

Like if, while can contain an else clause:

while (expression):        suite 1 else:        suite 2

Like if's else, while's else repeatedly tests the expression. If the expression is true, the first suite is executed. If the expression is false, or becomes false during the loop, else's suite is executed, and the while loop ends. If the executed suite contains a break statement, the loop terminates, and the else suite is not executed.

Continuing with our address book example, we'll use the else clause to add the option of quitting the program by sending an email of the address book to someone say, me. Typing in quit when we get the name means that we want to break not send the email. Entering " " (empty string) means that we want to execute the statements in the else clause and send the email. Of course, we won't actually send any email, so the emailData() function is commented out.

name = " " while (name != ""):        name = raw_input("Enter in the name: ")        if (name == ""):               continue        elif (name == "quit"):               break        phone_number = raw_input("Enter in the phone number: ")        address_line1 = raw_input("Enter address line one: ")        if (address_line1 == ""):               continue        address_line2 = raw_input("Enter address line two: ")        address_line3 = raw_input("Enter address line three: ")        #do something useful with the addresses else:        print("send the email to Rick")        #emailAddresses("rick_m_hightower@emailcompany.com")

Let's break down the changes made to the program.

First, if the while clause encounters an empty string for the name variable, it exits the loop.

while (name != ""):

If we pass an empty string for name, the continue clause kicks in, returning execution to the beginning of the while statement. Then the expression in the while clause is evaluated. The empty string there allows the while loop to terminate gracefully, as opposed to breaking out, so the else clause is executed.

elif (name == "quit"):             break

The elif clause in the if statement ensures that, if the name string equals quit, we break out of the loop (we terminate ungracefully). So the else clause isn't executed, allowing us to quit without sending the email, and I don't get my address list.

else:        print("send the email to Rick")        #emailAddresses("rick_m_hightower@emailcompany.com")

Here we've added the else clause to the while loop with the same indentation as that of the while clause of the while statement. Try executing this script.

The for Statement

The for statement repeatedly executes a suite of statements as it iterates through the items in a sequence. It appears as

for item in sequence :        suite

The expression should be a valid sequence (a tuple, string, or list). At the beginning of each iteration, the next item in the sequence is assigned to the item variable, and the suite is executed. This continues until all items have been dealt with.

To illustrate for, let's say that we have a list of email addresses for a monthly newsletter.

>>> email_list = ["rick_m_hightower@emailcompany.com", "adam_s_carr@hottermail.com", "bill_g_smith@hottestmail.com"] >>> >>> for address in email_list: ...     print ("Sending email to " + address) ...     # sendEmail(address, "Nothing new here") Sending email to rick_m_hightower@emailcompany.com Sending email to adam_s_carr@hottermail.com Sending email to bill_g_smith@hottestmail.com >>>

Like the while loop, the for loop uses an else clause when there are no more items in the list, else is executed. The break and continue statements work in for as they do in while.

The range() Function and for Loops

The for loop in Python can be used similarly to the for loop in Java and C with the range() function, whose purpose is to return a list of numeric values. The simplest example is a list of 1 through 9 in increments of 1.

>>> range(1,10) [1, 2, 3, 4, 5, 6, 7, 8, 9]

Other examples of range() follow. Respectively, they illustrate 1 through 20 by increments of 2; 0 through 100 by increments of 10; -100 through 200 by increments of 30; and 100 through -100 by increments of 20.

>>> range(1, 20, 2) [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] >>> range (0, 100, 10) [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] >>> range (-100, 200, 30) [-100, -70, -40, -10, 20, 50, 80, 110, 140, 170] >>> range (100, -100, -20) [100, 80, 60, 40, 20, 0, -20, -40, -60, -80]

To create a loop that iterates from 0 through 100 by increments of 10, we enter

>>> for x in range(0, 100, 10): ...     print("x equals " + `x`) ...

which outputs

x equals 0 x equals 10 x equals 20 x equals 30 x equals 40 x equals 50 x equals 60 x equals 70 x equals 80 x equals 90

Or we can iterate backward from 100 to 0 by decrements of 10 by entering

>>> for x in range (100, 0, -10): ...     print("x equals " + `x`) ...

which outputs

x equals 100 x equals 90 x equals 80 x equals 70 x equals 60 x equals 50 x equals 40 x equals 30 x equals 20 x equals 10
xrange()

xrange() is nearly identical to range(), except that it doesn't create individual items in a range until requested to do so, which makes it more efficient than range() for large ranges. Here's an example of xrange(), called xrange.py, followed by its output:

print ("This for loop uses xrange, which lazily creates members in the range") for x in xrange (-1000000000, 1000000000):       if( (x % 100000) == 0): print (`x`)       if (x == -999900000): break print ("Get ready to hit control C") print ("This for loop uses range") for x in range (-1000000000, 1000000000):       if( (x % 100000) == 0): print (`x`)       if (x == -999900000): break >>> import xrange This for loop uses xrange, which lazily creates members in the range -1000000000 -999900000 Get ready to hit control C This for loop uses range Out of Memory

Notice that when we try to create the second range we run out of memory. In essence, the second range() tries to create a list containing 2 billion integers, each 32 bits wide (4 bytes). For this we need a computer with 8 billion bytes, or 8 gigabytes, of memory.

Putting It All Together

Now it's time to create a program that uses everything we've learned so far. This program will generate a list of house prices and find their average (mean, mode, and median) and range. The following sections will describe each function in turn.

getRange()

getRange() iterates through a set of numbers passed to it and calculates the minimum and maximum values. It then returns these values and their range in a tuple.

def getRange (nums):        min = 300000000        max = -300000000 for item in nums:        if (item > max): max = item        if (item < min): min = item return (min, max, max-min)

First getRange() declares two variables, min and max. The min variable refers to a very large number, so the first item extracted from the list is less than that number and is assigned the min value. The max variable contains a negative number, so the first item extracted will be more than the large negative value and is assigned to the max variable.

Making getRange() More Efficient

The getRange() example will work only if the numbers passed to it are in the range of min and max. To make it more general purpose, we can use either of the following:

from java.lang import Double from java.lang import Double 

and then either of these:

min = Double.MAX_VALUE max = Double.MIN_VALUE min = Integer.MAX_VALUE max = Integer.MIN_VALUE 

This will make the function work well with Integer or Double types. The question is how well it will work with Long types. We'll have our answer shortly.

To figure min and max, getRange() iterates through the nums sequence.

for item in nums:       if (item > max): max = item       if (item < min): min = item

The expression item > max determines if the item's value is greater than max. If so, max is assigned to it, as expressed by this compound statement:

if (item > max): max = item

The following compound statement indicates that the item's value is less than min, so it's assigned to min:

if (item < min): min = item

When the loop stops iterating through the values, getRange() returns min, max, and max-min (range).

return (min, max, max-min)

The approach just described is a simple one, but it has a flaw. It works only if the numbers passed to xrange() are within max-min. The solution is the nums variable, which is a sequence with an intrinsic operation (otherwise known as a built-in function) for finding min and max in a list. nums is an improvement over getRange() because it's much shorter and can work with all numeric types as well as all Longs, Floats, and Doubles at their maximum range of precision. With nums there's no for loop and no figuring out what max and min should be initialized to (that is, given a default value).

Here's an example of nums:

def getRange2 (nums):       return (min(nums), max(nums), max(nums)-min(nums))

getMean()

The getMean() function figures out the mean of a number sequence. It iterates through the sequence, adding all of the values together and storing them in sum. It then figures out the mean by dividing sum by the sequence length.

In the following getMean() example, notice the use of the sample argument, the for loop, the if and else clauses, and the len() built-in function (which determines the length of a sequence).

def getMean (nums, sample):              """        Define mean that finds two types of mean,        namely: population mean and sample mean        """              sum = 0.0      # holds the value of sum                     #                     # iterate through the sequence of        # numbers and sum them               for x in nums:                     sum = sum + x                     #                     # Check to see if this is a sample mean               if(sample):                     average = sum / (len(nums)-1)                     #                     # Else it is a population mean               else:                     average = sum / len(nums)               return average

Here's the breakdown.

First we create a variable called sum that holds the sum.

sum = 0.0

Then we iterate through the nums sequence, accumulating the value of the item x.

for x in nums:      sum = sum + x

Next, using the sample argument, we check to see if this is a sample mean. If so, we figure the average by dividing sum by the number of items in nums less 1, or we divide the sum by the number of items in the nums sequence.

if(sample):        average = sum / (len(nums)-1)        #        # Else it is a population mean else:        average = sum / len(nums)

Finally we return the average.

return average

getMode()

The getMode() function finds the value that repeats most often in a sequence. First it duplicates the sequence so it can modify it. Then it iterates through the items in the nums sequence, counting occurrences of the current items with the built-in count() method. Once getMode() counts an item, it removes it from the duplicated sequence.

In the getMode() example that follows, notice the use of the for and while loops, the if statement, the count() method, and the nested for loop.

def getMode (nums):        """Find the number that repeats the most. """              #              # make a duplicate copy of the nums argument        duplicate = nums[:]        highest_count = -100        mode = None              #              # calculate the highest_count and the mode        for item in nums:              count = duplicate.count(item)              if (count == 0): continue              if (count > highest_count):                     highest_count = count                     mode = item              while(duplicate.count(item) > 0):                     duplicate.remove(item)        return mode

Let's break this down.

First we duplicate the nums sequence and create a variable to hold highest_count (and assign it a negative starting number) and a variable to hold the nums sequence mode.

duplicate = nums[:] highest_count = -100 mode = None

Next we iterate through each item in nums and count duplicate nums occurrences.

for item in nums:       count = duplicate.count(item)       if (count == 0): continue

As we iterate through the list, we see if the current count is greater than highest_count. If it is, we assign it to highest_count and item to mode.

if (count > highest_count):       highest_count = count       mode = item

Continuing our iteration, we remove all occurrences of the item from the duplicate sequence with the following while statement:

while(duplicate.count(item) > 0):        duplicate.remove(item)

Finally we return mode.

return mode

getMedian()

The getMedian() function finds the middlemost value once the sequence is sorted. In the following getMedian() example, notice the use of the modulus operator (%), the if statement, the else clause, and the built-in sort() operation.

def getMedian (nums):              "Find the Median number"                    # create a duplicate since        # we are going to modify it              seq = nums[:]                    #sort the list of numbers              seq.sort()              median = None # to hold the median value              length = len(seq) # to hold the length of the seq                    # Check to see if the length is an even number              if ( ( length % 2) == 0):                           # since it is an even number                           # add the two middle numbers together                    index = length / 2                    median = (seq[index-1] + seq[index]) /2.0        else:                           # since it is an odd number                           # just grab the middle number                    index = (length / 2)                    median = seq[index]        return median

Once again, let's break it down.

First we duplicate the nums sequence and sort the duplicate (seq).

seq.sort()

Then, with the expression length%2, we check if the length is an even number. (Remember that the modulus operator returns the remainder.) If the length is even, the expression length%2 returns zero, and we calculate the median by adding together the two most central numbers and figuring their average.

length = len(seq) if ( ( length % 2) == 0):       index = length / 2       median = (seq[index-1] + seq[index]) /2.0

If the length is odd, we grab the middle value.

else:       index = (length / 2)       median = seq[index]

Finally we return the median.

return median

reportStatistics()

reportStatistics() calls all of the functions implemented in our house prices example getMean(), getMode(), getRange(), getMedian(), and nested dictionaries and stores their return values in two dictionaries, averages and ranges. It puts these dictionaries in another dictionary called report, which it returns.

def reportStatistics (nums):              # get central tendencies       averages = {              "mean":getMean(nums,0),              "median":getMedian(nums),              "mode":getMode(nums)              }              # get range       range = getRange(nums)              # put ranges in a dictionary       ranges = {              "min":range[0],              "max":range[1],              "range":range[2]              }       report = {              "averages": averages,              "ranges": ranges              }       return report

Breaking this down, we first get the averages mean, median, and mode using getMean(), getMedian(), and getMode(). Notice that "mean":getMedian defines a key/value pair.

averages = {        "mean":getMean(nums,0),        "median":getMedian(nums),        "mode":getMode(nums)        }

Then we get the range parameters min, max, and max-min from getRange(). We use range[0], range[1], and range[2] in the returned sequence. Notice that "min":range[0] defines a key/value pair in the ranges dictionary.

       # get range range = getRange(nums)        # put ranges in a dictionary ranges = {        "min":range[0],        "max":range[1],        "range":range[2]        }

Now we define a dictionary called report that contains the averages and ranges dictionaries.

report = {        "averages": averages,        "ranges": ranges        }

Lastly we return the report dictionary.

return report
Using reportStatistics()

RunReport() uses reportStatistics() to get the report dictionary it needs to print out the report. In the following runReport() example, note the use of the string format operator (%), the %f format directive, nested dictionaries, and the use of the format operator with a dictionary.

from chap4 import reportStatistics house_in_awahtukee = [100000, 120000, 150000, 200000, 65000, 100000] report = reportStatistics(house_in_awahtukee) range_format = """ Range: The least expensive house is %(min)20.2f The most expensive house is %(max)20.2f The range of house price is %(range)20.2f """ average_format = """ Averages: The mean house price is %(mean)20.2f The mode for house price is %(mode)20.2f The median house price is %(median)20.2f """ print range_format % report["ranges"] print average_format % report["averages"]

Here's the output:

Range: The least expensive house is 65000.00 The most expensive house is 200000.00 The range of house price is 135000.00 Averages: The mean house price is 122500.00 The mode for house price is 100000.00 The median house price is 110000.00

Summary

Control flow allows programs to execute nonsequentially using the if, while, and for compound statements. if conditionally executes a statement, while executes a statement while a condition is true, and for iterates through a sequence. All three can contain else clauses that execute when the if condition is false, when it becomes false, or when the items in a list are or become empty, respectively.

As compound statements, if, while, and for contain clauses. Clauses contain suites and control their execution. if contains if, elif, and else clauses; while contains while and else clauses; and for contains for and else clauses. Within the while and for statements, break and continue, as their names imply, break out of a loop and continue a loop from the top.

Specific to the for statement are the range() and xRange() functions. range() returns a list of numbers; xRange() returns a number in a range only when requested to do so.

We created a sample application to compute range, mean, mode, and median for a group of house prices. The application highlighted the following key concepts from Chapters 1 through 4:

  • for loop

  • while loop

  • if statement

  • if and else clauses

  • Nested loops

  • len(), count(), and sort()

  • Modulus (%)

  • %f format directive

  • Nested dictionaries

  • Use of a dictionary with the format operator

CONTENTS


Python Programming with the JavaT Class Libraries. A Tutorial for Building Web and Enterprise Applications with Jython
Python Programming with the Javaв„ў Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython
ISBN: 0201616165
EAN: 2147483647
Year: 2001
Pages: 25

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net