repetition -- loops in in an algorithm -- and how to implement loops in Python

KhaledMaarof
Chapter4-LoopsandListsinPython.pdf

An Introduction to Computer Science with Java, Python and C++ Community College of Philadelphia edition Copyright 2018 by C.W. Herbert, all rights reserved.

Last edited January 21, 2019 by C. W. Herbert

This document is a draft of a chapter from An Introduction to Computer Science with Java, Python and C++, written by Charles

Herbert. It is available free of charge for students in Computer Science courses at Community College of Philadelphia during the

Spring 2019 semester. It may not be reproduced or distributed for any other purposes without proper prior permission.

Please report any typos, other errors, or suggestions for improving the text to cherbert@ccp.edu

Chapter 4 – Loops and Lists in Python

Chapter 4 – Loops and Lists in Python .......................................................................................................... 1

Chapter 4 – Loops and Lists in Python .......................................................................................................... 2

Chapter 4 Learning Outcomes ...................................................................................................................... 2

Repetition in Algorithms ................................................................................................... 3

Loop Control Variables .......................................................................................................................... 4

Lesson 4.2 Pre-Test Loops and Post-Test Loops ....................................................................................... 6

Pre-Test Loops ....................................................................................................................................... 6

Post-Test Loops ..................................................................................................................................... 7

While Loops in Python - Sentinel Loops and Count Controlled Loops .............................. 8

Sentinel Loops ....................................................................................................................................... 8

Count-controlled Loops ...................................................................................................................... 11

Random numbers in Python ........................................................................................... 12

Using the randrange() function ........................................................................................................... 14

In Class Exercise ...................................................................................................................................... 16

Python lists ...................................................................................................................... 17

Using for statements with Python lists ............................................................................................... 17

Exercise ............................................................................................................................................... 18

Python list operations ......................................................................................................................... 19

Chapter Exercises .................................................................................................................................... 20

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 2

Chapter 4 – Loops and Lists in Python

This chapter examines repetition in algorithms and in Python programming. Repetition in an

algorithm or computer program is also known as looping, because part of an instruction set is

repeated, forming a loop in the program logic.

The difference between pre-test loops with the test for repetition at the beginning of the loop and

post-test loops with the test for repetition at the end of the loop is discussed. The difference

between loops that are count-controlled and loops that are not count-controlled is also discussed.

The concepts of a list in Python and iterating a list are also discussed.

Chapter 4 Learning Outcomes

Upon completion of this chapter students should be able to:

• describe the concept of repetition in an algorithm;

• describe the difference between a pre-test loop and a post-test loop and why

a pre-test loop is often preferred;

• list and describe the four major components of a pre-test loop in a computer

program;

• describe the difference between a count-controlled loop and a sentinel loop,

and the three pieces of information needed for the counter in a count-

controlled loop;

• create Python code that includes pre-test loops, post-test loops, count-

controlled loops, sentinel loops, and nested loops.

• describe the concept of a list in Python and how to create a list of data items.

• Create code that iterates a list using the Python for statement, and which

processes the data items in the list with each iteration.

Note: This chapter refers to the Python 3 programming language and assumes that you

have the Python 3 language ready to use on your computer. Appendix A describes

downloading and installing Python.

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 3

Repetition in Algorithms

Repetition occurs whenever part of an algorithm is repeated, forming a loop in the algorithm. The loop

is a repetition sequence.

In Chapter 3 we saw conditional execution – algorithms that branched into different paths based on

some condition in the form of a Boolean expression. A loop is created when an algorithm branches

backward following such a condition, as shown by the pseudocode and flowchart below.

The Boolean condition in this algorithm is (x <= 10). The condition appears following the word while

instead of the word if that is used in binary branching. In pseudo-code, as in many programming

languages, the word while indicates that the path of the algorithm returns to the conditional expression

when the block of code following the while statement is finished being executed, forming a loop. This

use of the word while originated in the Algol language, so it is common in Algol-derived languages such

as C, C++, Java, and Swing.

A while statement forms a test to see if a loop should be executed. Each time the Boolean condition in

the while statement is true, the computer will execute the block of code, then go back to the condition

again. When the condition is no longer true, the block of code will be ignored, and the computer will

move on to whatever comes next in the algorithm.

It is possible that the while condition could be false the first time it is encountered, which means the

loop will not be executed in this run through the algorithm. It is also possible that the while condition

will always be true, which means the loop will always be executed, forming an infinite loop.

A small round circle or dot is used on a flowchart to show where the path that forms the loop rejoins the

previously executed part of the algorithm. This symbol is called a connector and is only used to show

where separate paths of logic in an algorithm come together.

Figure 1 –

a loop in an algorithm

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 4

The algorithm illustrated above prints the numbers from 1 to 10. Before the loop starts, x is set to 1.

If the condition (x ≤ 10) is true, the value of x is printed, x is incremented by 1, then the condition is

checked again. This continues until the condition is false – until x is no longer less than or equal to 10.

The last time through the loop, 10 will be printed, then x is set to 11. When the condition is checked this

time around, the loop terminates because the condition is now false, 11 is not less than or equal to 10.

A while statement is not the only statement used for branching. Just as there are several different kinds

of branching routines, there are several different kinds of loops. The loop shown in Figure 1 on the

previous page is an example of a count-controlled pre-test loop. Loops are either count-controlled loops

or sentinel loops. They are either post-test loops or pre-test loops. We will examine these differences in

this chapter.

Loop Control Variables

As we just saw, a condition is tested each time through a loop to determine whether to repeat the loop

again or terminate the loop and move on. The condition should be either a boolean expression or a

function that returns a Boolean value. The condition should include at least one loop control variable. A

loop control variable is a variable used in a boolean expression to determine if a loop should be

repeated. Sometimes the acronym LCV is used to refer to a loop control variable. Any type of variable

may be used in a loop control variable, as long as the overall expression evaluates to a Boolean value, as

in the condition from above, (X<=10).

Here are some examples of while statements with Boolean expressions containing loop control variables

using Python syntax:

• while count < 10 : # count is number.

• while !(name == “END”) : # name is a string.

• while age >= 18 and age <= 65 : # age is a number. This checks for a range of values.

• while citizen: # citizen is a Boolean variable.

• while angle == math.pi: # angle is a number. This is a troublesome condition.

• while (abs(angle – math.pi) < .001) # angle is a number. This works better.

Why is angle == math.pi troublesome? Tests for equality of variables can be troublesome because

floating point values could be rounded off differently, so two floating point values may not be exactly

equal. This is especially true for irrational numbers, which cannot be expressed as a ratio of integers -- a

fraction with an integer numerator and an integer denominator. 3.14159 does not equal 3.141592.

Instead of testing for equality, we can test to see if two values are really close to one another, by seeing

if the difference between them is less than a given small value, as in the last condition above: (abs(angle

– math. pi) < .001) The absolute value function is used in the condition to see if the magnitude of the

difference between angle and π is less than .001. It tests to see if angle is really close to π. We can

make this test as accurate as needed. In general, this is a good way to compare floating point values that

may be irrational or that may be rounded off for some other reason.

A loop may have more than one loop control variable, such as in the following while statement:

while (all the doors are not painted AND we still have paint left)

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 5

In programming terms, the statement might look more like this:

while ( (unpaintedDoorCount > 0) and (amountOfPaint > 0) ):

Both unpaintedDoorCount and amountOfPaint are loop control variables. The loop will only repeat if

both parts of the condition are true.

Here is an example using an OR condition:

while (at least 12 years old OR at least 60 inches tall)

In programming terms, the statement might look more like this:

while (age >= 12) or (height >= 60) :

Both age and height are loop control variables. In this case, the loop will repeat if either of the two parts

of the condition is true.

In the next few sections we will look at the different kinds of loops and how to implement them in

Python.

While Loops in Other Languages

While loops in the Java, C, C++, Microsoft C#, and the Apple Swift programming languages are almost

identical to while loops in Python. Here are some examples of a while loop to print the numbers from

one to ten in several programming languages. Almost all use syntax derived from ALGOL 68.

Notice that Python uses indenting to indicate the body of a loop, where many other languages use

braces { }, or word pairs, such as do and end.

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 6

Lesson 4.2 Pre-Test Loops and Post-Test Loops

The test to determine if part of an algorithm should be repeated could occur at the beginning of a loop

or at the end of a loop. If the test occurs at the beginning of a loop, the loop is known as a pre-test loop.

If the test occurs at the end of the loop, the loop is known as a post-test loop. In this section we will

look at the structure of pre-test loops and post-test loops.

Pre-Test Loops

A pre-test loop is a loop in which the test to determine whether or not to go through the loop comes

before the process that is to be executed within the loop. There are four parts to every pre-test loop:

• Loop Initialization: set the first value of the loop control variable

• Loop Test: test the loop control variable to see if the loop should be executed

• Loop Processing: instructions defining the part of the algorithm to be repeated

• Loop Update: change the value of at the loop control variable

The body of a loop includes all of the instructions in the loop’s block of code – the processing and the

update. The four parts of the loop are identified in the following pseudocode:

The update in a pre-test loop usually occurs at the end of the body of the loop, after the processing.

This is a convention adopted by many programmers to make the logic in an algorithm easier to

understand. It’s a good idea to do things this way to avoid confusion, but it is not absolutely necessary

to do so.

count = 1

while count ≤ 10:

print (count)

count += 1

• The initialization happens before the loop starts. All of a loop’s control variables should be initialized before a loop starts. The loop shown here has only one control variable, count.

• The test is the condition in the while statement. This loop’s condition tests to see if count is less than or equal to 10.

• The processing in this example is just one instruction. It could be many instructions or even a call to run a different method or function, which we will see in later chapters.

• The update is the part of the algorithm where the value of at least one control variable is changed. If the values of all of a loop’s control variables remain the same each time through the loop, then we have an infinite loop. The loop’s update is the statement +=1, which increments count.

Figure 2 –

structure of a pre-test loop

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 7

Post-Test Loops

A post-test loop is a loop in which the test to determine whether or not to repeat the loop comes after

the body of the loop. Here is our one to ten algorithm with a post-test loop:

start

x = 1

do

print x

increment x

while (x <= 10)

stop

This post-test algorithm produces the same results as the pre-test algorithm we saw earlier. A

do…while structure establishes a post-test loop, with do at the beginning of the loop and the while

condition at the end of the loop. We might see this in pseudocode, and in languages such as Java and

C++, but there is no do...while structure, nor any other structure for post-test loops, in Python. This was

a conscious decision by Guido van Rossum based on principles of computer science. Many computer

scientists believe that post-test loops are dangerous and can lead to software with undesired side

effects. Here is an example:

Imagine a method that erases hard drives, which are numbered starting with zero. If this is a pre-test

loop, as in the example on the left, the program first asks if we want to erase a hard drive, then does so

if we say yes. In the post-test loop algorithm on the right it erases a drive first, then asks if we want to

erase another. What happens if someone tries the program on the left to see what it does? …the

program on the right? What could go wrong with a post-test loop used to control nuclear weapons?

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 8

Of course, not all programmers agree, and there is a way to implement post-test loops in Python, even

though they are discouraged. We will see more about this later in the course.

While Loops in Python - Sentinel Loops and Count Controlled Loops

Python has a while statement that can be used to implement pre-test loops. The Python while statement

is similar to an if statement, with a condition, followed by a colon, then an instruction or block of code

indented to form the body of the loop. It looks very much like the pseudocode in the last section.

Both sentinel loops and count-controlled loops can be implemented with the while statement. We will

look at sentinel loops first, then count controlled loops.

Sentinel Loops

a sentinel is a marker that signals when a loop should be terminated. The sentinel could be a value or a

terminating condition. A sentinel loop continues until it encounters a sentinel. The sentinel could be

input from a user, a marker at the end of a data file, or any other condition that the software can

determine, such as a printer running out of paper.

The concept of a sentinel is important in reading data files. Usually there is a special value at the end of

a file called an end of file marker. We can write a loop to read data in from a data file until the end of

file marker is encountered. Here is a pseudocode examples of such a loop. We will see more about this

when we study data files later in the semester.

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 9

read the first data item from a file

while not(end of file):

print (data item)

read next data item

The loop above will continue to read data from the file, one item at a time, until the sentinel condition is

met – the data is the end-of-file marker. The EOF marker is a sentinel value. The condition is a sentinel

condition.

In older computers that used punched cards, data would be read in from a deck of cards, with one record on each card. The last card in the deck, called a trailer card, marked the end of the deck. Sentinel values are sometimes still referred to as trailer values.

These images from a British university circa 1970 show a deck of cards, students creating decks of cards with keypunch machines, and an operator loading a deck of cards into a card reader.

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 10

Python while statements can be used for sentinel loops. Here is an example with user input:

The loop reads a string value from the keyboard each time it is executed. The input to initialize the loop

control variable before the while command is called a priming read. The loop will continue until the

user inputs the string "done".

Notice that the input is a string. if it is not the string "done", then it should be a value entered by the

user. The loop converts the input string to an integer before proceeding.

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 11

Count-controlled Loops

It could be argued that every loop is a sentinel loop, checking for a sentinel in a data set or looking for a

condition that ends a loop and thus acts like a sentinel. However, if the condition that controls

repetition is based on counting, then we have a count-controlled loop. A count-controlled loop is a loop

in which the loop control variable is an iterated numeric variable. An iterated numeric variable

changes in discrete steps from one value to another. When we count to ten, we are changing a value

from one to ten in steps of one. The pre-test and post-test loops we saw at the beginning of this

chapter were count-controlled loops.

The loop control variable in a count-controlled loop is a called a counter. There are three things we

need to know about the counter to set up a loop control variable:

• the initial value

• the final value

• the increment

In the one to ten loops we saw, the initial value is 1, the final value is 10, and the increment is 1.

We could have a negative increment, also called a decrement, but only if the final value is less than the

starting value. For example, we could have an initial value of 10, a final value of 1, and an increment of

-1, which would cause our loop to go from 10 down to 1.

Be careful – if the initial value and the final value don’t match the increment – for example if the initial

value is 1 the final value is 10 and the increment is -1 (negative one) – then we could end up with an

infinite loop. The values of the counter would start at 1, then be 0, then -1, then -2, and theoretically

never reach 10. However, the program will eventually stop on most computers. One of three things will

happen:

• the computer will timeout automatically if the program continues to run for a certain

amount of time. Some operating systems have a built-in mechanism for this.

• The computer will run out of memory. Of course, this only applies if more memory is used

each time through a loop.

• the loop control variable will go out of bounds. Each data type has an acceptable range of

values. Eventually the value of the loop control variable will be out of bounds -- out of the

acceptable range for that data type.

In Python, one of these three things will eventually happen, but it could take a while to go out of bounds

– integer numeric values often have a range of values from -2,147,483,648 to +2,147,483,647. The

following Python 3 code will tell you the largest integer available on the platform you are using:

import sys

print(sys.maxsize)

The increment for a counter in a count-controlled loop does not need to be 1 or -1. It could be almost

any number. Here are some examples. Can you identify the output from each one?

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 12

Example A

x = 1

while ( x < 10):

print (x)

x = x + 1

Example B

x = 10

while ( x ≥ 1):

print (x)

x = x -1

Example C

x = 1

while ( x ≤ 100):

print (x)

x = x + 2

Example D

x = 2

while ( x ≤ 100):

print (x)

x = x + 2

Example E

x = 0.0

while ( x ≤ 10.0):

print (x)

x = x + 0.5

The Python += operator can be used to increment a value. x += 1 is equivalent to x = x + 1. This is

known as the augmented assignment operator for addition. There are augmented assignment operators

in Python for each of the mathematical operators: +, -, /, //, *, and ** have augmented

assignment operator +=, -=, /=, //=, *=, and **=.

x -= 2 is the same as x = x - 2, and so on.

Random numbers in Python

Python has a module named random that can be used to generate pseudo-random numbers. A pseudo-

random number is a number that appears to be random, but which really follows a pattern that can be

duplicated. Unlike true random numbers, pseudo-random numbers are predictable.

The Python random module contains a function named random() that will generate and print a random

floating point number between 0 and 1, including 0 but not including 1. 0.0 <= random() < 1.0.

To use the random() function, or any of the functions in the random module, it must be imported into

your Python programs.

import random

#declare variables

rand = 0.0 # a randomly generated number

# generate and print a random number using the random() function

rand = random.random()

print(rand, " is a randomly generated number")

Under identical circumstances, a Python program will generate the same pattern of random numbers

every time. This can be useful when doing a statistical experiment or a simulation in which we would like

to use the same set of random number each time we repeat the experiment, but is not desirable for

things like games that should be random, not pseudo-random.

To control pseudo-random numbers, and to make them harder to predict, Python has a seed(n) function

that can be used to seed its random number generator. To seed a random number generator is to place

the generator in a state to pick a specific number. In Python, n can be any number.

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 13

# seed the random number generator

rand = random.seed(1)

# generate and print a random number using the random() function

rand = random.random()

print(rand, " is a randomly generated number using seed(1).\n")

If we use the seed() function with no parameter, python will initialize the random number generator

using the system clock. Since the system clock is accurate to billionths of a second, this mimics a truly

random number for most purposes. However, keep in mind that a program could still be written

allowing someone to access the system and predict the numbers generated.

# seed the random number generator using the system clock

rand = random.seed()

# generate and print a random number using the random() function

rand = random.random()

print(rand, " is a randomly generated number using the system clock.\n")

Almost any value can be used as seed for the random number generator, including strings. Python uses

a formula to turn the value of n in seed(n) into a number that can seed the random number generator.

# seed the random number generator with a string

rand = random.seed("Hello")

# generate and print a random number using the random() function

rand = random.random()

print(rand, " is a randomly generated number using 'Hello'.\n")

The value returned by random.random() is in the range 0.0 ≤ n < 1.0. What if we want to pick an integer

from 1 to 10, including 1 and 10? We start by multiplying by the number 10. 0 times 10 is 0. 1 times 10

is 10. If 0.0 ≤ n < 1.0, and we multiply n by 10, then 0.0 ≤ n < 10.0.

But we still don’t have an integer, and notice the range is < 10, so ten is not included in the possible

values yet. Our next step is to type cast the result into an integer. Remember, y = (int) x; turns y into an

integer by truncating x. It does not round off x, it chops off the decimal. If 0.0 ≤ n < 10.0, and we

truncate the value, we get 0 ≤ n < 10. The number will be an integer in the set {0, 1, 2, 3,… 9} .

Next we just add 1 to the value and now it is in the set {1,2,3…,10} which is what we want.

So, to generate an integer in the range from 1 to 10, including 1 and 10 with Math.random() use:

x= 1+ int(random.random() * 10)

This does exactly what we want – picks a number in the range 0.0 ≤ n < 1.0, multiply by 10, truncate it

to be an integer, then add 1.

So, to set a variable x equal to a random integer between 1 and b, including 1 and b, the assignment

statement should be:

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 14

x= 1 + int(random.random() * b) where b is the high endpoint of the range of values.

The following examples show how to generate random integers for specific ranges of values. Generating

random floating point numbers is similar, but we do not typecast the values to integers.

pick a door – 1, 2, or 3

door = 1 + int(random.random() * 3)

simulate rolling a pair of dice, each between 1 and 6

d1 = 1 + int(random.random() * 6)

d2 = 1 + int(random.random() * 6)

total = d1 +d2;

pick a card from a deck of cards

suit = 1 + int(random.random() * 4); # if 1 print “hearts”, if 2 print “clubs”, etc.

rank = 1 + int(random.random() * 13); # 1 is an “ace”, 11 is a “jack”, 12 is a “queen”, 13 is a “king”

Using the randrange() function

Python has a randrange() function that will generate a random number within a given range of values,

which is a shortcut to using the mathematical methods discussed above. It can be used in several ways.

With a single parameter, randrange(n) will generate an integer from zero up to but not including n.

With two parameters, randrange(n1, n2) will generate an integer from n1 up to but not including n2.

The Python program randomDemo.py demonstrates the random functions discussed above.

# randomDemo.py

# program to demonstrate generating random numbers

# last edited Oct. 8, 2018 by C. Herbert for CSCI 111

import random

#declare variables

rand = 0.0 # a randomly generated number

count = 0.0 # a loop counter

# generate and print a random number using the random() function

rand = random.random()

print(rand, " is a randomly generated number.\n")

# seed the random number generator

rand = random.seed(1)

# generate and print a random number using the random() function

rand = random.random()

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 15

print(rand, " is a randomly generated number using seed(1).\n")

# seed the random number generator using the system clock

rand = random.seed()

# generate and print a random number using the random() function

rand = random.random()

print(rand, " is a randomly generated number using the system clock.\n")

# generate and print a set of random numbers using the randrange(n) function

print("Here is a set of random numbers between zero and ten.")

count = 1

while count <= 5 :

rand = random.randrange(11)

print("\t", rand)

count +=1

# end while

print("\n")

# generate and print a set of random numbers using the randrange(n1,n2)

function

print("Here is a set of random numbers between 10 and 20")

count = 1

while count <= 5 :

rand = random.randrange(10,21)

print("\t", rand)

count +=1

# end while

.

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 16

In Class Exercise

The following pseudocode is from the example of a guessing game found in Chapter 3, starting on page

19. Create a Python program to implement this design.

start

int pick # the number the computer picks

int guess = 0 # the user’s guess, initialized to zero

int count = 0 # the number of guesses

pick = a random number between 1 and 100

print “I am thinking of a number between 1 and 100.”

print ”Try to guess what it is.”

print” Your guess?”

user inputs guess # get value of guess from the keyboard input

while (guess ≠ pick) # set up a loop to repeat until the user guesses the

number

{

increment count # keep track of how many guesses

if (guess < pick) # in the loop guess cannot equal pick: it will be low or

high

print “Too low. Try again.”

else

print “too high. Try again.”

print ”Your guess?”

user inputs guess # get value of guess from the keyboard input

} #end while (guess ≠ pick), the loop ends when guess = pick

print “Correct. The number is ” + pick

print “It took you ” + count + “ guesses”

stop

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 17

Python lists

In addition to simple data types such as integer and string, Python has several compound data types that

can be used to store more than one value. The most commonly used among these is the Python list. A

list in Python is a linear, sequential, indexed set of values that can be represented by a single variable.

Values in the list are separated by commas, with the entire list enclosed in square brackets. Here is an

example of a Python list defined by an assignment statement.

seventiesMovies = ["The Godfather", "Chinatown", "Taxi Driver", "Rocky"]

An individual value in a Python list can be accessed using the name of the list followed by its index

number in square brackets, which is an integer starting at zero for the first item and following in

sequence for each additional item. in the list above, seventiesMovies[0] is "Godfather",

seventiesMovies[1] is "Chinatown", and so on.

Notice that the highest index value will be one less than the number of items in the list because we

started counting at zero. If the list has n item, then the highest index will be n-1.

Many programming languages have a built-in linear, sequential, indexed data structure called an array.

Python does not have arrays, but Python lists are very similar to arrays.

The values in a Python list can be any valid Python data type. Python's loose binding of variable names

to their locations and data types allows values of different data types to be used in the same list,

although all values in a Python list are often the same data type for practical reasons.

Lists can be printed using the print() function, just as with other data types.

Using for statements with Python lists

A python for statement can be used to iterate a list, as in the following:

for movie in seventiesMovies:

print(movie)

The name of a variable follows the word for, with the name of the list following the word in. The for loop

will be executed once for each value in the list, with the variable referring to each value from the list in

turn. In this example, the variable movie will refer to seventiesMovies[0] for the first iteration of the

loop, seventiesMovies[1] for the second iteration of the loop, and so on, up to seventiesMovies[3}.

Individual values in Python lists can be assigned with assignment statements, such as:

seventiesMovies[2] = "Star Wars"

This only works if the list item already exists. In the case above, "Star Wars" replaces "Taxi Driver" in the

list. The following will not work, because our list does not have 5 items, so there is no

seventiesMovies[4]:

seventiesMovies[4] = "Annie Hall"

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 18

The if…in statement can be used to test for membership in a Python list:

if "Godfather" in seventiesMovies:

print("Yes, Godfather is in the list.")

Exercise

The Python statements shown as examples in the section above are listed below. Try them in order in

the Python shell to see the results. for and if statements can be entered on a single line, but your may

need tp press enter twice at the end of the line.

(The statements can also each be cut and pasted from this text.)

seventiesMovies = ["The Godfather", "Chinatown", "Taxi Driver", "Rocky"]

for movie in seventiesMovies: print(movie)

seventiesMovies[2] = "Star Wars"

for movie in seventiesMovies: print(movie)

seventiesMovies[4] = "Annie Hall"

if "The Godfather" in seventiesMovies: print("Yes, Godfather is in the list.")

Your results should be similar to those shown below:

Notice that the error message generated by seventiesMovies[4] = "Annie Hall" tells us that

the "list assignment index is out of range." This is because we attempted to assign a value using index 4

and the list only contains 4 items with index values 0 through 3. As mentioned above, the highest index

in a list with n items in n-1.

The length of a Python list can be changed; in other words, Python lists are dynamically sized. This is one

of the operations that can be formed by Python's list methods. Some commonly used list operations,

functions, and methods are described below.

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 19

Python list operations

Several operations can be performed on Python lists. The two most common operations are list

concatenation and list repetition.

Two Python lists can be concatenated to combine one longer list, as in the following:

newList = ["A", "B", "C"] + ["D", "E", "F"]

This can also be done with list variables.

List repetition can be used to create a list with repeated items:

Hello = ["Hello, world!"] * 3

This can also be done with lists that have more than one item:

dataset = ["city", "state", "zip"] * 12

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 20

Chapter Exercises

1. Multiplication Table

A set of nested loops can be used to print a multiplication table using formatted print statements.

1 2 3 4 5 6 7 8 9

1 1 2 3 4 5 6 7 8 9

2 2 4 6 8 10 12 14 16 18

3 3 6 9 12 15 18 21 24 27

4 4 8 12 16 20 24 28 32 36

5 5 10 15 20 25 30 35 40 45

6 6 12 18 24 30 36 42 48 54

7 7 14 21 28 35 42 49 56 63

8 8 16 24 32 40 48 56 64 72

9 9 18 27 36 45 54 63 72 81

Write a program to print such a multiplication table.

2. Celsius to Fahrenheit Table

Write a program to print a Celsius to Fahrenheit conversion table that a traveler could use to look up

temperatures while traveling. The formula is F = ( 9

5 C) + 32.

The table should include integer Celsius degrees from 0 to 40. Your program does not need to use integers, but the table should display the Celsius temperature, then the Fahrenheit accurate to one- tenth of a degree. The first four entries from the table could look like this:

Celsius Fahrenheit

0 32.0

1 33.8

2 35.6

3 37.4

4 39.2

3. Guessing Game

The guessing game that asks a user to pick a number from 1 to 100 is described in Chapter 3, starting on

on pages 19 with pseudocode, sample output, and a flowchart. It uses branching, repetition, and the

generation of random numbers. Your task is to create the game in Python. You should submit the game

along with your programming lab report as described in Chapter 3.

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 21

4. Printing Patterns

Nested for loops can print patterns of stars, such as the example below:

for i in range(1,6):

for j in range(1,11):

print("*", end =" ")

print("")

Output from this program:

**********

**********

**********

**********

**********

Your task is to write similar Python code using nested loops to print each the following patterns:

*

**

***

****

*****

*

**

***

****

*****

*

***

*****

******

*

***

*****

*******

*

***

*****

*******

***

***

***

Consider the numeric relationship between the row number and the number of starts in that row, as well as the relationship between the row number and the number of blank spaces to be printed before the stars are printed.

5. International Gymnastics Scoring

We wish to write a program to quickly calculate gymnastics scores for an international competition. The

program should have a loop to ask the user for the scores from each of the six judges, numbered 1

through 6 for anonymity. Your program should add each score to a sum inside the loop, then calculate

and display the average score after the loop is finished. Scores are in the range 0 to 10 with one decimal

place, such as 8.5. The average should be displayed with two decimal places.

Here is a sample of the output:

Score for Judge 1: 8.5

Score for Judge 2: 8.7

Score for Judge 3: 8.4

Score for Judge 4: 9.1

Score for Judge 5: 8.9

Score for Judge 6: 9.0

The average score is: 8.77

6. Write a program similar to number 5, above, but in this case it should work no matter how many judges

there are. The user will enter a -1.0 as the score to signal that there are no more judges.

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 22

7. Fibonacci Numbers

The Fibonacci sequence is one of the most commonly found patterns in nature. It starts with 0 and 1, then each term in the sequence is generated by adding the previous two terms. The first few terms are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. Numbers that appear in the sequence are called Fibonacci numbers. Write a program that uses a loop to generate and display the first 20 Fibonacci numbers. Your program can start by printing 0 and 1, then work from there for the next 18 Fibonacci numbers.

8. Trigonometric Table

Write a program to print the sine and cosine for angles between 0 degrees and 90 degrees in increments

of 10 degrees. Your program should use the functions in the Math library – Math.sin() and Math.cos().

The trigonometric functions work in radians, so for each angle, your program will need to convert

degrees to radians, then find and print the sine and cosine.

For example, y = math.sin(math.radians(x)) # calculates the sin of x degrees

angle sin Cos

10 0.174 0.985

20 0.342 0.940

30 0.500 0.866

40 0.643 0.766

50 0.766 0.643

60 0.866 0.500

70 0.940 0.342

80 0.985 0.174

90 1.000 0.000

9. Test for Divisibility

If the remainder from dividing A by B is zero, then A is a multiple of B ( A is evenly divisible by B). For

example, the remainder from dividing 6, 9, or 12 by 3 is 0, which means 6, 9, and 12 are all multiples of

3. Write a program to print the numbers from 1 to 25, and on the line next to each number, print

messages if the number is a multiple of 2, 3, or 5. Here is a sample of the output:

1

2 multiple of 2

3 multiple of 3

4 multiple of 2

5 multiple of 5

6 multiple of 2 multiple of 3

7

8 multiple of 2

9 multiple of 3

10 multiple of 2 multiple of 5

Intro to CSCI with Java, Python, and C++ Chapter 4 – Loops and Lists in Python page 23

10. Estimate of a Definite Integral

A loop in a computer program can be used to approximate the value of a definite integral. We can break

the integral into rectangles, find the area of each rectangle then add the areas together to get the total

area, as shown in the accompanying diagram. In practice, we could make the width of the rectangles

progressively smaller, then run the loop again, until we achieved the desired accuracy.

y = 9-x2

area under the curve

estimated by rectangles

As the width of the rectangles gets progressively smaller, their total area gets closer to the total area

under the curve. This is an old method that predates Calculus. Both Leibnitz and Newton used this

method, eventually developing calculus from the concept of infinitesimals, which, in the case of our

rectangles, would amount to asking, what would the total area be if we had very many rectangles with

very small width?

This was tedious by hand, but we now have computers. We can set the width of the rectangle. The

height of the rectangle is the y value at point x. So for example, if we need to solve:

∫ 9 − 𝑥2 𝑑𝑥 −3

+3

The starting point is -3, the ending point is +3, and the height of the rectangle at each value of x in

between the two is 9 − 𝑥2 where y at each x is the height of the rectangle at that x. We can start with a

width of 0.1, and write a loop like this:

totalArea = 0

for x in range(-3, +3.1, 0.1): # x is -3.00, then -2.9, then -2.8, etc.

y = 9- x**x # the height is the y value at each x

area = y * 0.1 # the width is the increment, in this case 0.1

totalArea = totalArea + area

# end for

When the loop is finished, totalArea is the total area of the rectangles, which is an approximation of the

area under the curve.

Your task is to write a Python program that implements this algorithm for the definite integral used in

this example. Run the loop several times, each time with a smaller increment, until your result does not

change by more than .01 from the previous run of the program.

— End of Chapter 4 —