Sequences items in a list by displaying a successive number beside each item

Skip to main content

Intermediate Python

Level up your data science skills by creating visualizations using Matplotlib and manipulating DataFrames with pandas.

Related

20 Data Analytics Projects for All Levels

Explore our list of data analytics projects for beginners, final-year students, and professionals. The list consists of guided/unguided projects and tutorials with source code.

SQL vs Python: Which Should You Learn?

In this article, we will cover the main features of Python and SQL, their main similarities and differences, and which one you should choose first to start your data science journey.

Javier Canales Luna •

12 min

Text Data In Python Cheat Sheet

Welcome to our cheat sheet for working with text data in Python! We've compiled a list of the most useful functions and packages for cleaning, processing, and analyzing text data in Python, along with clear examples and explanations, so you'll have everything you need to know about working with text data in Python all in one place.

Python Sets and Set Theory Tutorial

Learn about Python sets: what they are, how to create them, when to use them, built-in functions and their relationship to set theory operations.

Pandas Tutorial: DataFrames in Python

Explore data analysis with Python. Pandas DataFrames make manipulating your data easy, from selecting or replacing columns and indices to reshaping your data.

See MoreSee More

Modern computers can do millions or even billions of instructions a second. With the techniques discussed so far, it would be hard to get a program that would run by itself for more than a fraction of a second.

Practically, we cannot write millions of instructions to keep the computer busy. To keep a computer doing useful work we need repetition, looping back over the same block of code again and again. There are two Python statement types to do that: the simpler

1
2
3
8 loops, which we take up shortly, and
1
2
3
9 loops, which we take up later, in .

Two preliminaries:

  1. The value of already defined variables can be updated. This will be particularly important in loops. To prepare for that we first follow how variables can be updated in an even simpler situation, where statements are just executed in textual order.
  2. Sequence types are used in
    1
    2
    3
    8 loops. We will look at a basic sequence type:
    for count in [1, 2, 3]: 
        print(count) 
        print('Yes' * count) 
    
    1.

Then we put this all together. This is a long section. Go slowly and carefully.

1.13.1. Updating Variables

The programs so far have defined and used variables, but other than in early shell examples we have not changed the value of existing variables. For now consider a particularly simple example, just chosen as an illustration, in the example file

for count in [1, 2, 3]: 
    print(count) 
    print('Yes' * count) 
2:

1
2
3
4
5

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    

Can you predict the result? Run the program and check. Particularly if you did not guess right, it is important to understand what happens, one step at a time. That means keeping track of what changes to variables are made by each statement.

In the table below, statements are referred to by the numbers labeling the lines in the code above. We can track the state of each variable after each line is executed. A dash is shown where a variable is not defined. For instance after line 1 is executed, a value is given to x, but y is still undefined. Then y gets a value in line 2. The comment on the right summarizes what is happening. Since x has the value 3 when line 2 starts, x+2 is the same as 3+2. In line three we use the fact that the right side of an assignment statement uses the values of variables when the line starts executing (what is left after the previous line of the table executed), but the assignment to the variable y on the left causes a change to y, and hence the updated value of y, 10, is shown in the table. Line 4 then changes x, using the latest value of y (10, not the initial value 5!). The result from line 5 confirms the values of x and y.

LinexyComment13- 2355=3+2, using the value of x from the previous line331010=2*5 on the right, use the value of y from the previous line47107=10-3 on the right, use the value of x and y from the previous line5710print: 7 10

When we create such a table, the order of execution will always be the order of the lines in the table. In this simple sequential code, that also follows the textual order of the program. Following each line of execution of a program in the proper order of execution, carefully, keeping track of the current values of variables, will be called playing computer. A table like the one above is an organized way to keep track.

1.13.2. The for count in [1, 2, 3]: print(count) print('Yes' * count) 1 Type

Lists are ordered sequences of arbitrary data. Lists are the first kind of data discussed so far that are mutable: the length of the sequence can be changed and elements substituted. We will delay the discussion of changes to lists until a further introduction to objects. Lists can be written explicitly. Read the following examples

['red', 'green', 'blue']
[1, 3, 5, 7, 9, 11]
['silly', 57, 'mixed', -23, 'example']
[] # the empty list
[ [7, 11], [1], [] ] # list containing three elements; each a list

The basic format is a square-bracket-enclosed, comma-separated list of arbitrary data.

1.13.3. The for count in [1, 2, 3]: print(count) print('Yes' * count) 4 Function, Part 1

There is a built-in function

for count in [1, 2, 3]: 
    print(count) 
    print('Yes' * count) 
4, that can be used to automatically generate regular arithmetic sequences. Try the following in the Shell:

list(range(4))
list(range(10))

The general pattern for use is

for count in [1, 2, 3]: 
    print(count) 
    print('Yes' * count) 
6sizeOfSequence
for count in [1, 2, 3]: 
    print(count) 
    print('Yes' * count) 
7

This syntax will generate the integers, one at a time, as needed . If you want to see all the results at once as a list, you can convert to a

for count in [1, 2, 3]: 
    print(count) 
    print('Yes' * count) 
1 as in the examples above. The resulting sequence starts at 0 and ends before the parameter. We will see there are good reasons to start from 0 in Python. One important property of sequences generated by
for count in [1, 2, 3]: 
    print(count) 
    print('Yes' * count) 
9 is that the total number of elements is
for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
print('Done counting.')
for color in ['red', 'blue', 'green']:
    print(color)
0: The sequence omits the number
for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
print('Done counting.')
for color in ['red', 'blue', 'green']:
    print(color)
0 itself, but includes 0 instead.

With more parameters, the

for count in [1, 2, 3]: 
    print(count) 
    print('Yes' * count) 
4 function can be used to generate a much wider variety of sequences. The elaborations are discussed in and .

In computer jargon, producing values of a sequence only as needed is called lazy evaluation.

1.13.4. Basic 1 2 38 Loops

Try the following in the Shell. You get a sequence of continuation lines before the Shell responds. After seeing the colon at the end of the first line, the Shell knows later lines are to be indented.

Be sure to enter another empty line. (Just press

for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
print('Done counting.')
for color in ['red', 'blue', 'green']:
    print(color)
4.) at the end to get the Shell to respond. :

1
2
3

for count in [1, 2, 3]: 
    print(count) 
    print('Yes' * count) 

This is a

1
2
3
8 loop. It has the heading starting with
1
2
3
8, followed by a variable name (
for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
print('Done counting.')
for color in ['red', 'blue', 'green']:
    print(color)
7 in this case), the word
for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
print('Done counting.')
for color in ['red', 'blue', 'green']:
    print(color)
8, some sequence, and a final colon. As with function definitions and other heading lines, the colon at the end of the line indicates that a consistently indented block of statements follows to complete the
1
2
3
8 loop.

1
2
3
8 item
for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
print('Done counting.')
for color in ['red', 'blue', 'green']:
    print(color)
8 sequence
for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
    print('Done counting.') # changed so indented
for color in ['red', 'blue', 'green']:
    print(color)
2

indented statements to repeat; may use item

The block of lines is repeated once for each element of the sequence, so in this example the two lines in the indented block are repeated three times. Furthermore the variable in the heading (

for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
print('Done counting.')
for color in ['red', 'blue', 'green']:
    print(color)
7 here) may be used in the block, and each time through it takes on the next value in the sequence, so the first time through the loop
for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
print('Done counting.')
for color in ['red', 'blue', 'green']:
    print(color)
7 is 1, then 2, and finally 3. Look again at the output and see that it matches this sequence. A more detailed sequence is given, playing computer, in the table:

Linecountcomment11start with the first element of the list21print 131‘yes’ * 1 is ‘yes’; print yes12change count to the next element in the list22print 232‘yes’ * 2 is ‘yesyes’; print yesyes;13change count to the next element in the list23print 333‘yes’ * 3 is ‘yesyesyes’; print yesyesyes; done with list

When executing step by step, note that the

1
2
3
8 loop heading serves two purposes:

  • Each time the heading line executes, it implicitly assigns a new value to the variable name you use in place of item.
  • After each execution of the heading line, the statements in the indented block are executed, generally making use of the the new value for the variable assigned in the heading.

Note

When playing computer with a loop, the same line numbers can reappear over and over, because the

1
2
3
8 loop heading line and the indented body under it are each executed repeatedly. Each time one of these lines is executed, it must be listed separately, in time sequence!

A

1
2
3
8 loop is technically a single compound statement. Its level of indentation is considered to be the level of indentation of its heading.

When you used the Shell to enter a loop, there was a reason that the interpreter waited to respond until after you entered an empty line: The interpreter did not know how long the loop block was going to be! The empty line is a signal to the interpreter that you are done with the loop block, and hence ready to execute the complete compound loop statement.

Look at the following example program

for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
    print('Done counting.') # changed so indented
for color in ['red', 'blue', 'green']:
    print(color)
8, and run it.

for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
print('Done counting.')
for color in ['red', 'blue', 'green']:
    print(color)

In a file, where the interpreter does not need to respond immediately, the blank line is not necessary. Instead, as with a function definition or any other format with an indented block, you indicate being past the indented block by dedenting. Here the following

for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
    print('Done counting.') # changed so indented
for color in ['red', 'blue', 'green']:
    print(color)
9 statement has the same level of indentation as the
1
2
3
8 loop heading. Because they have the same level of indentation, they are executed in sequence. Hence in the code above, “Done Counting.” is printed once after the first loop completes all of its repetitions. Execution of the program ends with another simple loop.

As with the indented block in a function, it is important to get the indentation right. Alter the code above, so the fourth line is indented:

for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
    print('Done counting.') # changed so indented
for color in ['red', 'blue', 'green']:
    print(color)

Predict the change, and run the code again to test.

Loops are one of the most important features in programming. While the

1
2
3
8 loop syntax is pretty simple, using them creatively to solve problems (rather than just look at a demonstration) is among the biggest challenges for many learners at an introductory level. One way to simplify the learning curve is to classify common situations and patterns, and give them names. One of the simplest patterns is illustrated in all of the
1
2
3
8 loop examples so far, a simple for-each loop: For each element of the sequence, do the same sort of thing with it. Stated as more Pythonic pseudo-code:

1
2
3
8 item
for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
print('Done counting.')
for color in ['red', 'blue', 'green']:
    print(color)
8 sequence
for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
    print('Done counting.') # changed so indented
for color in ['red', 'blue', 'green']:
    print(color)
2

do something with the current item

(It would be even more like English if

1
2
3
8 were replace by
addPick('animal', userPicks)
addPick('food', userPicks)
addPick('city', userPicks)
7, but the shorter version is the one used by Python.)

In the

1
2
3
8 loop examples above, something is printed that is related to each item in the list. Printing is certainly one form of “do something”, but the possibilities for “do something” are completely general!

We can use a for-each loop to revise our first example in the Tutorial. Recall the code from madlib.py:

addPick('animal', userPicks)
addPick('food', userPicks)
addPick('city', userPicks)

Each line is doing exactly the same thing, except varying the string used as the cue, while repeating the rest of the line. This is the for-each pattern, but we need to list the sequence that the cues come from. Read the alternative:

for cue in ['animal', 'food', 'city']:  # heading
    addPick(cue, userPicks)             # body

Seeing this feature requires the ability to abstract the general pattern from the group of examples. This is essential for using loops effectively.

If you wish to see or run the whole program with this small modification, see the example

addPick('animal', userPicks)
addPick('food', userPicks)
addPick('city', userPicks)
9. A common naming convention is used in the program: Each element in the list is a
for cue in ['animal', 'food', 'city']:  # heading
    addPick(cue, userPicks)             # body
0, while the list with all the elements is named with the plural
for cue in ['animal', 'food', 'city']:  # heading
    addPick(cue, userPicks)             # body
1. In later situations I make a list name be the plural of the variable name used for an individual item of the list.

Note the logic of the transformation between the two program versions: The alternative pieces of data are collected in the list in the

1
2
3
8 loop heading. A single variable name (here I chose
for cue in ['animal', 'food', 'city']:  # heading
    addPick(cue, userPicks)             # body
0) is used in the heading as a placeholder to refer to the current choice being handled, and the body refers to this variable
for cue in ['animal', 'food', 'city']:  # heading
    addPick(cue, userPicks)             # body
0 in place of the explicit data values included each time in the original no-loop version.

It is important to understand the sequence of operations, how execution goes back and forth between the heading and the body. Here are the details:

  1. heading first time: variable
    for cue in ['animal', 'food', 'city']:  # heading
        addPick(cue, userPicks)             # body
    
    0 is set to the first element of the sequence,
    for cue in ['animal', 'food', 'city']:  # heading
        addPick(cue, userPicks)             # body
    
    6
  2. body first time: since
    for cue in ['animal', 'food', 'city']:  # heading
        addPick(cue, userPicks)             # body
    
    0 is now
    for cue in ['animal', 'food', 'city']:  # heading
        addPick(cue, userPicks)             # body
    
    6, effectively execute
    for cue in ['animal', 'food', 'city']:  # heading
        addPick(cue, userPicks)             # body
    
    9 (Skip the details of the function call in this outline.)
  3. heading second time: variable
    for cue in ['animal', 'food', 'city']:  # heading
        addPick(cue, userPicks)             # body
    
    0 is set to the next element of the sequence,
    x = 3      # simple sequential code
    y = x + 2  # updating two variables
    y = 2*y        
    x = y - x      
    print(x, y)    
    
    01
  4. body second time: since
    for cue in ['animal', 'food', 'city']:  # heading
        addPick(cue, userPicks)             # body
    
    0 is now
    x = 3      # simple sequential code
    y = x + 2  # updating two variables
    y = 2*y        
    x = y - x      
    print(x, y)    
    
    01, effectively execute
    x = 3      # simple sequential code
    y = x + 2  # updating two variables
    y = 2*y        
    x = y - x      
    print(x, y)    
    
    04
  5. heading third time: variable
    for cue in ['animal', 'food', 'city']:  # heading
        addPick(cue, userPicks)             # body
    
    0 is set to the next (last) element of the sequence,
    x = 3      # simple sequential code
    y = x + 2  # updating two variables
    y = 2*y        
    x = y - x      
    print(x, y)    
    
    06
  6. body third time: since
    for cue in ['animal', 'food', 'city']:  # heading
        addPick(cue, userPicks)             # body
    
    0 is now
    x = 3      # simple sequential code
    y = x + 2  # updating two variables
    y = 2*y        
    x = y - x      
    print(x, y)    
    
    06, effectively execute
    x = 3      # simple sequential code
    y = x + 2  # updating two variables
    y = 2*y        
    x = y - x      
    print(x, y)    
    
    09
  7. heading done: Since there are no more elements in the sequence, the entire
    1
    2
    3
    8 loop is done and execution would continue with the statement after it (not indented).

In this example the data values are just a few given literals, and there is only one line in the repeated pattern. Hence the use of a

1
2
3
8 loop is not a big deal, but it makes a simple example! This looping construction would be much handier if you were to modify the original mad lib example, and had a story with many more cues. Also this revision will allow for further improvements in , after we introduce more about string manipulation.

1.13.4.1. Pattern Loop Exercise

Write a two-line for-each loop in a file

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
12 containing a call to the
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
13 function, so that this code with the for-each loop produces exactly the same printed output as the code in example file
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
14. The
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
14 code is shown below:

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
0

Execute both versions to check yourself. Hint 1: Hint 2:

1.13.4.2. Triple Exercise

Complete the following function. This starting code is in

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
16. Save it to the new name
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
17. Note the way an example is given in the documentation string. It simulates the use of the function in the Shell. This is a common convention:

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
1

The elements of the list in the
1
2
3
8 loop heading are not all of the same type.You need to use the loop variable twice in the loop body.

1.13.5. Simple Repeat Loop

The examples above all used the value of the variable in the

1
2
3
8 loop heading. An even simpler
1
2
3
8 loop usage is when you just want to repeat the exact same thing a specific number of times. In that case only the length of the sequence, not the individual elements are important. We have already seen that the
for count in [1, 2, 3]: 
    print(count) 
    print('Yes' * count) 
4 function provides an easy way to produce a sequence with a specified number of elements. Read and run the example program
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
22:

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
2

In this situation, the variable

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
23 is not used inside the body of the for-loop.

The user could choose the number of times to repeat. Read and run the example program

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
24:

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
3

When you are reading code, you look at variable names as they are introduced, and see where they are used later. In the simple repeat loops above, the loop variable

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
23 is introduced, because there must be a variable name there, but it is never used.

One convention to indicate the simple repeat loop variable is never used again, is to use the special variable name

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
26 (just an underscore), as in:

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
4

1.13.6. Successive Modification Loops

Suppose I have a list of items called

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
27, and I want to print out each item and number them successively. For instance if
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
27 is
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
29, I would like to see the output:

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
5

Read about the following thought process for developing this:

If I allow myself to omit the numbers, it is easy: For any

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
30 in the list, I can process it with

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
6

and I just go through the list and do it for each one. (Copy and run if you like.)

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
7

Clearly the more elaborate version with numbers has a pattern with some consistency, each line is at least in the form:

number item

but the number changes each time, and the numbers do not come straight from the list of items.

A variable can change, so it makes sense to have a variable

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
31, so we have the potential to make it change correctly. We could easily get it right the first time, and then repeat the same number. Read and run the example program
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
32:

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
8

Of course this is still not completely correct, since the idea was to count. After the first time number is printed, it needs to be changed to 2, to be right the next time through the loop, as in the following code: Read and run the example program

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
33:

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
9

This is closer, but still not completely correct, since we never get to 3! We need a way to change the value of number that will work each time through the loop. The pattern of counting is simple, so simple in fact that you probably do not think consciously about how you go from one number to the next: You can describe the pattern by saying each successive number is one more than the previous number. We need to be able to change

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
31 so it is one more than it was before. That is the additional idea we need! Change the last line of the loop body to get the example program numberEntries3.py. See the addition and run it:

1
2
3
4
5

['red', 'green', 'blue']
[1, 3, 5, 7, 9, 11]
['silly', 57, 'mixed', -23, 'example']
[] # the empty list
[ [7, 11], [1], [] ] # list containing three elements; each a list
1

It is important to understand the step-by-step changes during execution. Below is another table showing the results of playing computer. The line numbers are much more important here to keep track of the flow of control, because of the jumping around at the end of the loop.

Again note that the program line numbers in the Line column of the playing computer table are not all listed sequentially, because the

1
2
3
8 loop heading line and the indented body under it are each executed repeatedly.

For compactness, the variable

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
27 does not get its own column, since it always has the value shown in the comment in line 1:

lineitemnumbercomment1--set items to [‘red’, ‘orange’,’yellow’, ‘green’]2-1 3‘red’1start with item as first in sequence4‘red’1print: 1 red5‘red’22 = 1+13‘orange’2on to the next element in sequence4‘orange’2print 2 orange5‘orange’33=2+13‘yellow’3on to the next element in sequence4‘yellow’3print 3 yellow5‘yellow’44=3+13‘green’4on to the last element in sequence4‘green’4print 4 green5‘green’55=4+13‘green’5sequence done, end loop and code

The final value of number is never used, but that is OK. What we want gets printed.

Go through carefully and be sure you understand the meaning of each entry in the table, and the reason for the sequencing and the reason for the exact position of each entry in each step where it changes! In particular see how and why the line number for each successive row is not always one more than the previous row. In particular, see how the same sequence of numbered lines may be repeated in multiple places in the table. Without this understanding you will not be able to play computer yourself and really understand loops.

This short example illustrates a lot of ideas important to loops:

  • Loops may contain several variables.
  • One way a variable can change is by being the variable in a
    1
    2
    3
    8 loop heading, that automatically goes through the values in the
    1
    2
    3
    8 loop list.
  • Another way to have variables change in a loop is to have an explicit statement that changes the variable inside the loop, causing successive modifications.

There is a general pattern to loops with successive modification of a variable like

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
31 above:

  1. The variables to be modified need initial values before the loop (line 1 in the example above).
  2. The loop heading causes the repetition. In a for-loop, the number of repetitions is the same as the size of the list.
  3. The body of the loop generally “does something” (like print above in line 4) that you want done repeatedly.
  4. There is code inside the body of the loop to set up for the next time through the loop, where the variable which needs to change gets transformed to its next value (line 5 in the example above).

This information can be put in a code outline:

Initialize variables to be modified

Loop heading controlling the repetition:

Do the desired action with the current variables

Modify variables to be ready for the action the next time

If you compare this pattern to the for-each and simple repeat loops in , you see that the examples there were simpler. There was no explicit variable modification needed to prepare for the next time though the loop. We will refer to the latest, more general pattern as a successive modification loop.

Functions are handy for encapsulating an idea for use and reuse in a program, and also for testing. We can write a function to number a list, and easily test it with different data. Read and run the example program

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
40:

['red', 'green', 'blue']
[1, 3, 5, 7, 9, 11]
['silly', 57, 'mixed', -23, 'example']
[] # the empty list
[ [7, 11], [1], [] ] # list containing three elements; each a list
2

Make sure you can follow the whole sequence, step by step! This program has the most complicated flow of control so far, changing both for function calls and loops.

  1. Execution start with the very last line, since the previous lines are definitions

  2. Then

    x = 3      # simple sequential code
    y = x + 2  # updating two variables
    y = 2*y        
    x = y - x      
    print(x, y)    
    
    41 starts executing.

  3. The first call to

    x = 3      # simple sequential code
    y = x + 2  # updating two variables
    y = 2*y        
    x = y - x      
    print(x, y)    
    
    42 effectively sets the formal parameter

    ['red', 'green', 'blue']
    [1, 3, 5, 7, 9, 11]
    ['silly', 57, 'mixed', -23, 'example']
    [] # the empty list
    [ [7, 11], [1], [] ] # list containing three elements; each a list
    
    3

    and the function executes just like the flow followed in

    x = 3      # simple sequential code
    y = x + 2  # updating two variables
    y = 2*y        
    x = y - x      
    print(x, y)    
    
    43. This time, however, execution returns to main.

  4. An empty line is printed in the second line of main.

  5. The second call to

    x = 3      # simple sequential code
    y = x + 2  # updating two variables
    y = 2*y        
    x = y - x      
    print(x, y)    
    
    42 has a different actual parameter
    x = 3      # simple sequential code
    y = x + 2  # updating two variables
    y = 2*y        
    x = y - x      
    print(x, y)    
    
    45, so this effectively sets the formal parameter this time

    ['red', 'green', 'blue']
    [1, 3, 5, 7, 9, 11]
    ['silly', 57, 'mixed', -23, 'example']
    [] # the empty list
    [ [7, 11], [1], [] ] # list containing three elements; each a list
    
    4

    and the function executes in a similar pattern as in

    x = 3      # simple sequential code
    y = x + 2  # updating two variables
    y = 2*y        
    x = y - x      
    print(x, y)    
    
    43, but with different data and one less time through the loop.

  6. Execution returns to main, but there is nothing more to do.

1.13.7. Accumulation Loops

Suppose you want to add up all the numbers in a list,

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
47. Let us plan this as a function from the beginning, so read the code below. We can start with:

['red', 'green', 'blue']
[1, 3, 5, 7, 9, 11]
['silly', 57, 'mixed', -23, 'example']
[] # the empty list
[ [7, 11], [1], [] ] # list containing three elements; each a list
5

If you do not see what to do right away, a useful thing to do is write down a concrete case, and think how you would solve it, in complete detail. If

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
47 is
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
49, you would likely calculate:

2 + 6 is 8

8 + 3 is 11

11 + 8 is 19

19 is the answer to be returned.

Since the list may be arbitrarily long, you need a loop. Hence you must find a pattern so that you can keep reusing the same statements in the loop. Obviously you are using each number in the sequence in order. You also generate a sum in each step, which you reuse in the next step. The pattern is different, however, in the first line, 2+6 is 8: there is no previous sum, and you use two elements from the list. The 2 is not added to a previous sum.

Although it is not the shortest way to do the calculation by hand, 2 is a sum of 0 + 2: We can make the pattern consistent and calculate:

start with a sum of 0

0 + 2 is 2

2 + 6 is 8

8 + 3 is 11

11 + 8 is 19

19 is the answer.

Then the second part of each sum is a number from the list,

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
47. If we call the number from the list
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
51, the main calculation line in the loop could be

['red', 'green', 'blue']
[1, 3, 5, 7, 9, 11]
['silly', 57, 'mixed', -23, 'example']
[] # the empty list
[ [7, 11], [1], [] ] # list containing three elements; each a list
6

The trick is to use the same line of code the next time through the loop. That means what was

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
52 in one pass becomes the
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
53 in the next pass. One way to handle that is:

['red', 'green', 'blue']
[1, 3, 5, 7, 9, 11]
['silly', 57, 'mixed', -23, 'example']
[] # the empty list
[ [7, 11], [1], [] ] # list containing three elements; each a list
7

Do you see the pattern? Again it is

initialization

loop heading:

main work to be repeated

preparation for the next time through the loop

Sometimes the two general loop steps can be combined. This is such a case. Since

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
52 is only used once, we can just substitute its value (
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
53) where it is used and simplify to:

['red', 'green', 'blue']
[1, 3, 5, 7, 9, 11]
['silly', 57, 'mixed', -23, 'example']
[] # the empty list
[ [7, 11], [1], [] ] # list containing three elements; each a list
8

so the whole function, with the

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
56 statement is:

['red', 'green', 'blue']
[1, 3, 5, 7, 9, 11]
['silly', 57, 'mixed', -23, 'example']
[] # the empty list
[ [7, 11], [1], [] ] # list containing three elements; each a list
9

list(range(4))
list(range(10))
0

The example program

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
57 has the code above with the following line added at the end to test the function (not indented). Run
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
57.

list(range(4))
list(range(10))
1

The pattern used here is certainly successive modification (of the

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
53 variable). It is useful to give a more specialized name for this version of the pattern here. It follows an accumulation pattern:

initialize the accumulation to include none of the sequence (

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
60 here)

1
2
3
8 item
for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
print('Done counting.')
for color in ['red', 'blue', 'green']:
    print(color)
8 sequence
for count in [1, 2, 3]:
    print(count)
    print('Yes' * count)
    print('Done counting.') # changed so indented
for color in ['red', 'blue', 'green']:
    print(color)
2

new value of accumulation = result of combining item with last value of accumulation

This pattern will work in many other situations besides adding numbers.

English loop terminology: Of course you need to be able to go from an English description of a problem to a plan and then implement it in Python. In particular, it will be very important to realize when you will need your program to have a loop through a sequence. What are some common words or phrases that suggest a loop? After thinking for yourself, compare:

Once you see this need for a loop, you need to plan your code. There are a bunch of questions you can routinely ask yourself about fleshing out the outline for the loop part of your code:

initialization

loop heading:

main work to be repeated

preparation for the next time through the loop

  1. What is the sequence? What descriptive name can I give to the loop variable?
  2. Write the
    1
    2
    3
    8 loop heading. With this decided, you no longer need to think about the whole program at once: You can focus on what you do for one element, with the name you gave in the loop heading.
  3. What do I need to do for a single element of the sequence? Does this involve other variables? If so, how will I initialize them? Write this action into the body of the loop, using the loop variable.
  4. Does the main action involve a variable, other than the loop variable, that needs to change each time through the loop? If so, how do I relate the present and next values, and change the value to be ready for the next time through the loop? Writing the sequence for a specific example may help. Finally, code this update.

1.13.7.1. Play Computer sumList Exercise

Suppose the function

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
65, defined above, is called with the parameter
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
66. Play computer on this call, using the file
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
67, opened from an operating system window for the examples directory. Do not open in Idle. The file should come up in your usual word processor. Immediately save the file as
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
68, and fill in blank cells in the table.

Make sure there is a row in the table for each line executed in the program, with a separate line entry for each time a line is executed. In each row enter which program line is being executed, and show all changes caused to variables by the execution of that one line. Display line numbers as shown in the margin beside the example code in the Tutorial. (The separate Python files themselves do not show the line numbers.) A table is started for you below. The final row that you enter in your your table should be for an execution of line numbered 6 in the code, and your comment can be, “return 18”.

If the same variable value in one column repeats through several rows, it is more convenient just leave the later entries blank, rather than keep copying. With this convention, the current value of a variable is the last value recorded in a previous line in the table.

This is the first “Play Computer” exercise with a loop. Be sure to look back at the earlier play computer examples. The lines in the loop (and hence their line numbers) repeat multiple times as rows in the table, as you follow the loop one time through after another!

The original parameter, which does not change, does not have a column in the table, for compactness. The start of the table is shown below. As shown in the first comment, throughout the function call,

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
47 is

list(range(4))
list(range(10))
2

Linesumnumcomment1--set nums to [5, 2, 4, 7]; skip line 2 doc string3   

1.13.7.2. Test sumList Exercise

Write a program

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
70 which includes a
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
41 function to test the sumList function several times. Include a test for the extreme case, with an empty list.

1.13.7.3. Join All Exercise

* Complete the following function. This starting code is in

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
72. Save it to the new name
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
73. Note the way an example is given in the documentation string. It simulates the use of the function in the Shell. This is a common convention:

list(range(4))
list(range(10))
3

First Hint: Second Hint:

1.13.8. More Playing Computer

Testing code by running it is fine, but looking at the results does not mean you really understand what is going on, particularly if there is an error! People who do not understand what is happening are likely to make random changes to their code in an attempt to fix errors. This is a very bad, increasingly self-defeating practice, since you are likely to never learn where the real problem lies, and the same problem is likely to come back to bite you.

It is important to be able to predict accurately what code will do. We have illustrated playing computer on a variety of small chunks of code.

Playing computer can help you find bugs (errors in your code). Some errors are syntax errors caught by the interpreter in translation. Some errors are only caught by the interpreter during execution, like failing to have a value for a variable you use. Other errors are not caught by the interpreter at all - you just get the wrong answer. These are called logical errors. Earlier logical errors can also trigger an execution error later. This is when playing computer is particularly useful.

A common error in trying to write the

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
42 function would be to have the following code (extracted from
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
75):

['red', 'green', 'blue']
[1, 3, 5, 7, 9, 11]
['silly', 57, 'mixed', -23, 'example']
[] # the empty list
[ [7, 11], [1], [] ] # list containing three elements; each a list
9

list(range(4))
list(range(10))
5

You can run this code and see that it produces the wrong answer. If you play computer on the call to

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
76, you can see the problem:

Lineitemnumbercomment1--set items to [‘apples’, ‘pears’, ‘bananas’]3‘apples’-start with item as first in sequence4‘apples’1 5‘apples’11 print: 1 apples6‘apples’22 = 1+13‘pears’2on to the next element in sequence4‘pears’1 5‘pears’1print: 1 pears OOPS!

If you go step by step you should see where the incorrect 1 came from: the initialization is repeated each time in the loop at line 4, undoing the incrementing of

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
31 in line 6, messing up your count.

Warning

Always be careful that your one-time initialization for a loop goes before the loop, not in it!

Functions can also return values. Consider the Python for this mathematical sequence: define the function m(x) = 5x, let y = 3; find m(y) + m(2y-1):

1
2
3
4
5

list(range(4))
list(range(10))
7

This code is in example

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
78. A similar example was considered in , but now add the idea of playing computer and recording the sequence in a table. Like when you simplify a mathematical expression, Python must complete the innermost parts first. Tracking the changes means following the function calls carefully and using the values returned. Again a dash ‘-‘ is used in the table to indicate an undefined variable. Not only are local variables like formal parameters undefined before they are first used, they are also undefined after the termination of the function,

LinexyComment1-3  Remember definition of m4-3 5-3start on: print(m(y) + m(2*y-1)); first want m(y), which is m(3)133pass 3 to function m, so x =3233return 5*3 = 155-3substitute result: print(15 + m(2*y-1)), want m(2*y-1), which is m(2*3-1) = m(5)153pass 5 to function m, so x=5253return 5*5 = 255-3substitute result: print(15 + 25), so calculate and print 40

Thus far most of the code given has been motivated first, so you are likely to have an idea what to expect. You may need to read code written by someone else (or even yourself a while back!) where you are not sure what is intended. Also you might make a mistake and accidental write code that does something unintended! If you really understand how Python works, one line at a time, you should be able to play computer and follow at least short code sequences that have not been explained before. It is useful to read another person’s code and try to follow it. The next exercises also provides code that has not been explained first, or has a mistake.

1.13.8.1. Play Computer Odd Loop Exercise

* Work in a word processor (not Idle!), starting from example

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
79, and save the file as
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
80. The file has tables set up for this and the following two exercise.

Play computer on the following code:

['red', 'green', 'blue']
[1, 3, 5, 7, 9, 11]
['silly', 57, 'mixed', -23, 'example']
[] # the empty list
[ [7, 11], [1], [] ] # list containing three elements; each a list
9

list(range(4))
list(range(10))
9

Reality check: 31 is printed when line 6 finally executes. The start of the table for this exercise is shown below.

LinexynComment10   

1.13.8.2. Play Computer Error Exercise

* In a word processor add to the file

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
80, started in the previous exercise.

The following code is supposed to compute the product of the numbers in a list. For instance

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
82 should calculate and return 5*4*6=120 in steps, calculating 5, 5*4=20 and 20*6=120.

1
2
3
4
5

1
2
3
1

The code for this exercise appears in the example file

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
83.

A major use of playing computer is to see exactly where the data that you expect gets messed up. Play computer on a call to

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
82 until you see that it makes a mistake, and produces a wrong number. Then you can stop extending the table, just ending with a comment about how the error is now visible.

The table headings and the first row of the table for this exercise are shown below.

LinenprodComment1--Set nums to [5, 4, 6]2   

Then you can stop and fix it: First copy

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
83 to
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
86, and fix the new file (and save again!).

1.13.8.3. Play Computer Functions Exercise

* In a word processor once again add to the file

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
80, started in the previous exercises.

Play computer on the following code:

1
2
3

1
2
3
3

Reality check: 70 is printed.

The table headings and the first row of the table for this exercise are shown below.

LinexComment1-2 Remember f definition3  

You will revisit line 3 several times, with table lines for function

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
88 execution interspersed. Look at the example above which has a table showing function
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
89 returning a value twice!

1.13.9. The for count in [1, 2, 3]: print(count) print('Yes' * count) print('Done counting.') # changed so indented for color in ['red', 'blue', 'green']: print(color) 9 function keyword x = 3 # simple sequential code y = x + 2 # updating two variables y = 2*y x = y - x print(x, y) 91

By default the print function adds a newline to the end of the string being printed. This can be overridden by including the keyword parameter

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
91. The keyword end can be set equal to any string. The most common replacements are the empty string or a single blank. If you also use the keyword parameter
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
93, these keyword parameters may be in either order, but keyword parameters must come at the end of the parameter list. Read the illustrations:

1
2
3
4

is equivalent to

1
2
3
5

This does not work directly in the shell (where you are always forced to a new line at the end). It does work in a program, but it is not very useful except in a loop!

Suppose I want to print a line with all the elements of a list, separated by spaces, but not on separate lines. I can use the

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
91 keyword set to a space in the loop. Can you figure out in your head what this example file
x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
95 does? Then try it:

1
2
3
6

If you still want to go on to a new line at the end of the loop, you must include a print function that does advance to the next line, once, after the loop. Try this variation,

x = 3      # simple sequential code
y = x + 2  # updating two variables
y = 2*y        
x = y - x      
print(x, y)    
96

How would you identify a series of sequential steps to several levels?

To identify a series of sequential steps to several levels, you could use: a multilevel list. The feature that is a collection of formatting characteristics that can be applied to text or paragraphs is: style.

Which alignment spreads the text evenly between the left and right margins so that the text begins at the left margin and ends uniformly at the right margin?

Spreads text evenly between the left and right margins, so that text begins at the left margin and ends uniformly at the right margin. ... .

Which alignment positions text horizontally in the center of a line?

The text-align property is used to set the horizontal alignment of a text.

What is an arrangement of information organized into rows and columns?

Table. An arrangement of information organized into rows and columns. Template. An existing document that you use as a starting point for a new document; it opens a copy of itself, unnamed, and then you use the structure—and possibly some content, such as headings—as the starting point for a new document.