Module-5-INTEGRATIVE PROGRAMMING 2
Module-5-INTEGRATIVE PROGRAMMING 2
Tuguegarao City
Course Code :
Course Title : INTEGRATIVE PROGRAMMING 2
MODULE No. 05
TITLE: CONDITIONAL AND LOOPS 2
INTRODUCTION
LEARNING 1.
OUTCOMES
LEARNING 1.
OBJECTIVES
4.5. The for loop
The for loop processes each item in a sequence, so it is used with Python’s sequence data types - strings,
lists, and tuples.
The general form of a for loop is:
This is another example of a compound statement in Python, and like the branching statements, it has a
header terminated by a colon (:) and a body consisting of a sequence of one or more statements indented
the same amount from the header.
The loop variable is created when the for statement runs, so you do not need to create the variable before
then. Each iteration assigns the the loop variable to the next element in the sequence, and then executes
the statements in the body. The statement finishes when the last element in the sequence is reached.
This type of flow is called a loop because it loops back around to the top after each iteration.
Page 1
UNIVERSITY OF CAGAYAN VALLEY
Tuguegarao City
4.6. Tables
One of the things loops are good for is generating tables. Before computers were readily available,
people had to calculate logarithms, sines and cosines, and other mathematical functions by hand. To
make that easier, mathematics books contained long tables listing the values of these functions. Creating
the tables was slow and boring, and they tended to be full of errors.
When computers appeared on the scene, one of the initial reactions was, “This is great! We can use the
computers to generate the tables, so there will be no errors.” That turned out to be true (mostly) but
shortsighted. Soon thereafter, computers and calculators were so pervasive that the tables became
obsolete.
Well, almost. For some operations, computers use tables of values to get an approximate answer and
then perform computations to improve the approximation. In some cases, there have been errors in the
underlying tables, most famously in the table the Intel Pentium processor chip used to perform floating-
point division.
Although a log table is not as useful as it once was, it still makes a good example. The following
program outputs a sequence of values in the left column and 2 raised to the power of that value in the
right column:
Using the tab character ('\t') makes the output align nicely.
0 1
1 2
2 4
3 8
4 16
5 32
6 64
7 128
8 256
9 512
10 1024
11 2048
12 4096
4.7. The while statement
The general syntax for the while statement looks like this:
Page 2
UNIVERSITY OF CAGAYAN VALLEY
Tuguegarao City
while BOOLEAN_EXPRESSION:
STATEMENTS
Like the branching statements and the for loop, the while statement is a compound statement consisting
of a header and a body. A while loop executes an unknown number of times, as long at the
BOOLEAN EXPRESSION is true.
Here is a simple example:
number = 2
prompt = "What is the meaning of life, the universe, and everything? "
Notice that if number is set to 42 on the first line, the body of the while statement will not execute at all.
Here is a more elaborate example program demonstrating the use of the while statement
name = 'Harrison'
guess = input("So I'm thinking of person's name. Try to guess it: ")
pos = 0
Page 3
UNIVERSITY OF CAGAYAN VALLEY
Tuguegarao City
What you will notice here is that the while loop is more work for you — the programmer — than the
equivalent for loop. When using a while loop one has to control the loop variable yourself: give it an
initial value, test for completion, and then make sure you change something in the body so that the loop
terminates.
4.8. Choosing between for and while
So why have two kinds of loop if for looks easier? This next example shows a case where we need the
extra power that we get from the while loop.
Use a for loop if you know, before you start looping, the maximum number of times that you’ll need to
execute the body. For example, if you’re traversing a list of elements, you know that the maximum
number of loop iterations you can possibly need is “all the elements in the list”. Or if you need to print
the 12 times table, we know right away how many times the loop will need to run.
So any problem like “iterate this weather model for 1000 cycles”, or “search this list of words”, “find all
prime numbers up to 10000” suggest that a for loop is best.
By contrast, if you are required to repeat some computation until some condition is met, and you cannot
calculate in advance when this will happen, as we did in the “greatest name” program, you’ll need
a while loop.
We call the first case definite iteration — we have some definite bounds for what is needed. The latter
case is called indefinite iteration — we’re not sure how many iterations we’ll need — we cannot even
establish an upper bound!
4.9. Tracing a program
To write effective computer programs a programmer needs to develop the ability to trace the execution
of a computer program. Tracing involves “becoming the computer” and following the flow of execution
through a sample program run, recording the state of all variables and any output the program generates
after each instruction is executed.
To understand this process, let’s trace the execution of the program from The while statement section.
At the start of the trace, we have a local variable, name with an initial value of 'Harrison'. The user will
enter a string that is stored in the variable, guess. Let’s assume they enter 'Maribel'. The next line
creates a variable named pos and gives it an intial value of 0.
To keep track of all this as you hand trace a program, make a column heading on a piece of paper for
each variable created as the program runs and another one for output. Our trace so far would look
something like this:
Page 4
UNIVERSITY OF CAGAYAN VALLEY
Tuguegarao City
Tracing can be a bit tedious and error prone (that’s why we get computers to do this stuff in the first
place!), but it is an essential skill for a programmer to have. From a trace we can learn a lot about the
way our code works.
4.10. Abbreviated assignment
Incrementing a variable is so common that Python provides an abbreviated syntax for it:
>>> count = 0
>>> count += 1
>>> count
1
>>> count += 1
>>> count
2
>>> n = 2
>>> n += 5
>>> n
7
>>> n=2
>>> n *= 5
>>> n
10
>>> n -= 4
>>> n
6
>>> n //= 2
>>> n
3
Page 5
UNIVERSITY OF CAGAYAN VALLEY
Tuguegarao City
>>> n %= 2
>>> n
1
This program makes use of the mathematical law of trichotomy (given real numbers a and b, exactly
one of these three must be true: a > b, a < b, or a == b).
4.12. The break statement
The break statement is used to immediately leave the body of its loop. The next statement to be
executed is the first one after the body:
This prints:
12
16
done
4.13. The continue statement
This is a control flow statement that causes the program to immediately skip the processing of the rest
of the body of the loop, for the current iteration. But the loop still carries on running for its
remaining iterations:
Page 6
UNIVERSITY OF CAGAYAN VALLEY
Tuguegarao City
This prints:
12
16
24
30
done
4.14. Another for example
Here is an example that combines several of the things we have learned:
Trace this program and make sure you feel confident you understand how it works.
Here we’ve assigned a list of five elements to the variable students. Let’s print out each student name,
and the number of subjects they are enrolled for:
Page 7
UNIVERSITY OF CAGAYAN VALLEY
Tuguegarao City
Now we’d like to ask how many students are taking CompSci. This needs a counter, and for each
student we need a second loop that tests each of the subjects in turn:
You should set up a list of your own data that interests you — perhaps a list of your CDs, each
containing a list of song titles on the CD, or a list of movie titles, each with a list of movie stars who
acted in the movie. You could then ask questions like “Which movies starred Angelina Jolie?”
4.16. List comprehensions
A list comprehension is a syntactic construct that enables lists to be created from other lists using a
compact, mathematical syntax:
variable = [list]
newlist =[expression for item in iterable if condition == true]
[expr for item1 in seq1 for item2 in seq2 ... for itemx in seqx if condition]
output_sequence = []
for item1 in seq1:
Page 8
UNIVERSITY OF CAGAYAN VALLEY
Tuguegarao City
4.17. Glossary
append
To add new data to the end of a file or other data object.
block
A group of consecutive statements with the same indentation.
body
The block of statements in a compound statement that follows the header.
branch
One of the possible paths of the flow of execution determined by conditional execution.
chained conditional
A conditional branch with more than two possible flows of execution. In Python chained
conditionals are written with if ... elif ... else statements.
compound statement
A Python statement that has two parts: a header and a body. The header begins with a keyword
and ends with a colon (:). The body contains a series of other Python statements, all indented the
same amount.
Note
We will use the Python standard of 4 spaces for each level of indentation
condition
The boolean expression in a conditional statement that determines which branch is executed.
conditional statement
A statement that controls the flow of execution depending on some condition. In Python the
keywords if, elif, and else are used for conditional statements.
counter
A variable used to count something, usually initialized to zero and incremented in the body of a
loop.
cursor
An invisible marker that keeps track of where the next character will be printed.
decrement
Decrease by 1.
definite iteration
A loop where we have an upper bound on the number of times the body will be executed.
Definite iteration is usually best coded as a for loop.
delimiter
A sequence of one or more characters used to specify the boundary between separate parts of
text.
increment
Both as a noun and as a verb, increment means to increase by 1.
Page 9
UNIVERSITY OF CAGAYAN VALLEY
Tuguegarao City
infinite loop
A loop in which the terminating condition is never satisfied.
indefinite iteration
A loop where we just need to keep going until some condition is met. A while statement is used
for this case.
initialization (of a variable)
To initialize a variable is to give it an initial value. Since in Python variables don’t exist until
they are assigned values, they are initialized when they are created. In other programming
languages this is not the case, and variables can be created without being initialized, in which
case they have either default or garbage values.
iteration
Repeated execution of a set of programming statements.
loop
A statement or group of statements that execute repeatedly until a terminating condition is
satisfied.
loop variable
A variable used as part of the terminating condition of a loop.
nested loop
A loop inside the body of another loop.
nesting
One program structure within another, such as a conditional statement inside a branch of another
conditional statement.
newline
A special character that causes the cursor to move to the beginning of the next line.
prompt
A visual cue that tells the user to input data.
Page 10