This lesson covers some of Python's control constructs. Control constructs control the execution of other parts of a program. They allow portions to be skipped or repeated, depending on the input data. We will cover only a bit of this rather broad topic.
As before, open Idle.
Sometimes a program needs to test a variable, and take different action depending on its value. Here's a simple example:
There are several things to notice about this program.
if
construct tells Python to make a decision. The
if
keyword is followed by some condition Python can test for truth
or falsity. The test must be followed by a colon. This particular
test simply decides if two expressions are the same,
specifically if the value of response
is the string
'yes'.
else:
is executed
instead. The other group of statements is skipped.
The two groups are called branches; the first being the
true branch, and the second the false branch.
print
is not indented. Therefore it
is outside the if
and
is always run.
Here
is the reason why it was an error to place spaces before your
expression on Lesson 1: Python thinks
indented statements are part of an if
, or some other
control construct. When no such construct exists, Python
gets very upset.
The ==
in the last example is a comparison operator.
Python uses ==
for comparison since =
is already used for assignment. Here's the set of them:
a == b | Check that a equals b. |
a != b | Check that a does not equal b. |
a < b | Check that a is strictly less than b. |
a <= b | Check that a is less than or equal b. |
a > b | Check that a is strictly greater than b. |
a >= b | Check that a is greater than or equal b. |
We've discussed some of Python's data types: integer, floating point, and
string. Comparisons return another
type: boolean.†
The boolean
type has only two possible values: True
and False
.
Try some of these from the Python command line:
Generally, comparisons are used to compare similar types: numbers
to numbers, strings to strings, etc. When comparing strings to strings,
the inequalities compare using an odd sort of alphabetical order, where
all the upper case letters come before all the lower case
ones. Using this peculiar ordering,
the <
operator means "comes before".‡
Also note that the values compared may be any other expressions, as:
Boolean values can also be combined using the
boolean operators and
and or
.
These each take two booleans, and produce a boolean result.
And
produces true when both inputs are true; false otherwise.
Or
produces true when at least one of its inputs is true; false
otherwise.¤
What does that add up to? Probably just what you
were expecting:
and
before or
, but we can change the order using parentheses,
just as we might with a numerical expression such as 5 * (6 + 7)
.
Try a few.
Python's if
can get quite complex.
For one thing, the else
part may be omitted entirely, in which
case it does nothing after finding the test false. Also,
since the branches of an if
may contain any other Python statements,
they may contain other if
's. This is called nesting.
On top of all that,
Python's if
statements may be extended to check several
conditions. Here's an improved version of the last program:
elif
keyword is an abbreviation for else
if
.
Another important class of control constructs is repetition,
also called looping.
This simply means to repeat some section of code several times.
Python has two looping statements, while
and for
,
but we'll limit ourselves to the for
loop.
Here's a simple example:
The for
statement
just repeats a range of statements (the loop body) once for each
element in the list, in order.
Before running the body each time (before each iteration),
the for
loop sets an index variable to the
appropriate list value.
In this example, the index variable is n
, but any variable
may be used.
As with the if
, the for
statement ends
with a colon, and the body statements are indented.
In the above example, we gave an explicit list enclosed in brackets, but there are some other ways to make lists:
range
function
to create our list. The range
has a peculiarity similar
to the substring slice notation: it goes up to,
but excludes, the second number.
The second example shows that we can use a string
as a list of its characters.
It also demonstrates a common programming idiom: Using a counter
inside a loop. The counter count
is set to 1 before the
loop starts, the initialization. Each iteration of the
loop runs the statement count = count + 1
, which increases
the value of count
by one. This is the increment.
Look at the output to see how the values of count
change for each iteration.
Since any statement may be placed in a loop body, we can nest ifs or other loops within loops. For instance:
nchar
, which is incremented for each
character in the input string, and num_sp
which is incremented only
for those characters (spaces) that it wants to count.
Each counter represents the number of characters seen so far:
it starts at zero, and increases for each interesting character in
the input string. When the loop finishes, the counts are correct for the
whole input string.
E
's in the input string.
Include both the upper and lower case forms in your count.
'A'
, and also less than or equal to 'Z'
.
Likewise, lower case letters will be between 'a'
and 'z'
.
The above example loops count something. Counting is a kind of accumulation: each iteration adds something to the counter. It's also possible to accumulate strings. Here's one:
result
to accumulate the
output line. Result
is initialized to the empty string, and
each iteration adds one character.
For an input space, it adds a dash, otherwise it adds the
input character. The result is almost a copy of the input line,
except for the spaces.
if
in your loop for this one.
*
does when applied to a string and an
integer.
Most programming languages support some idea of a function or a procedure. We have used built-in Python functions, but Python also lets programmers to create their own. Here's an example:
larger
takes two values, figures out which one is
larger, and returns it to the caller.
As you can see, a Python
function definition starts with the word def
, followed by the the name of
the function, then a list of
parameter names enclosed in parentheses and separated
by commas. Parameters are variable names used to
pass values into the function; you may use
any legal variable names, and you may have number of parameters.
The parameter list is followed by a colon.
As before, the body of the function is a group of indented statements.
A function body may contain any of the regular Python statements,
plus the return
statement.
A function can be used in any Python expression, as larger
is
used in the print statements. This is
known as calling the function. In a call,
the function name is followed by a list of
arguments in parentheses. Each argument is an expression, and the
number of arguments must equal the number of parameters.
The value of each argument is assigned to the corresponding
parameter, then the function body is run. When the function body
executes a return
statement, the value it specifies becomes
the value of the function call. This value is returned to the
expression as the value of the function call.
For instance, consider the second print statement,
jane
is 8 and spot
is 12.
Python will:
a
the value 3 and b
the value 36.
if
test will
be false, the function will execute return b
, where b
is
36.
print
statement as the value of
the function call, where it is printed.
The function larger
shortens this example program considerably.
The function is called in five places. If each of those calls
were replaced with the code to perform the function, the program
would be considerably larger, and harder to understand.
Those are two major reasons why programmers use functions.
Another reason is to simplify the design process.
Any complex system is designed using subassemblies. An engineer who designs an automobile does not start organizing sheet metal and bolts into an automobile. He organizes the problem into subassemblies. Major subassemblies of an automobile are the engine, transmission, the suspension system, etc. Each of these subassemblies is further decomposed into smaller bits. The car is designed of large subassemblies, each of which is designed from smaller sub-subassemblies and so forth, until we finally get down to nuts, bolts and sheet metal. Functions provide the subassemblies a programmer uses to organize a complex program. The problem is divided into sub-steps, which are implemented in functions. These may call other functions, working down to individual statements in a program.
Enter and run this beast:
return
. When they don't
they are called as you see here,
in a statement alone, but not as part of a larger expression.
Some programming languages sensibly refer to functions of these type as
procedures rather than functions, but in Python they're all called
functions.
drline
, he doesn't need to
think about the whole program, just about what to do to generate one
particular line of output. When the programmer creates the main part of
the program which uses the function, he need only think about
reading the string and looping through, and the fact that we'll
have to do something called drline
for each character.
print
statements from
the madlib program from Lesson 2.
Make a function
which takes the various words as parameters and prints the
madlib with those values. Put it into a Python program that simply
prints the madlib three times with different values. Don't
take input values; just print. Your program will
produce the same output each time.
genline
which creates and returns a string. It takes
three parameters: the length of the string (which must be at least 2),
an end character, and
a content character. It returns a string of the specified length
starting and ending with the end character. For instance,
genline(9, "@", "=") returns "@=======@".
Place it in a Python program which calls genline
with various
parameters and prints the result so you can see it work.
genline
. It should request
a width and a height and produce a box, as follows:
genline
in three places, one for
the top line, once in a loop to generate the middle lines,
and once for the final line. Don't forget that space (' '
)is a
perfectly good character to send send to genline
.
Now our programs can condition or repeat code as required by the input. Functions allow use to separate out parts for design or reuse. This gives us enough tools to do a bit more. So far, our programs have been text-based: all typing. In Lesson 4, we'll modify images, and in Lesson 5 we'll take a look at GUIs.
*This indenting rule is peculiar to Python. Most languages use keywords or special symbols to delimit a block of controlled statements.
†For mathematician George Boole, who studied mathematical systems of this type.
‡The order actually comes from the character coding. Each character is assigned an arbitrary numerical code value. Characters are recorded by storing this code value in the computer's memory. The comparison operators simply compare the codes. It's sort of like having the class line up in order by Social Security number. The assignments are arbitrary, but most computers follow the ASCII coding standard so that they can all be arbitrary in the same way.
¤It's actually a little more complicated than that. If you care, look here.
Copyright 2005, 2006
Thomas W Bennet •
Image Credits
•
Terms of use:
Creative
Commons