What python programming statement do we use for condition-controlled iteration?

4.1. Conditional execution¶

4.1.1. The if statement¶

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement, which has the genaral form:

if BOOLEAN EXPRESSION:
    STATEMENTS

A few important things to note about if statements:

  1. The colon [:] is significant and required. It separates the header of the compound statement from the body.

  2. The line after the colon must be indented. It is standard in Python to use four spaces for indenting.

  3. All lines indented the same amount after the colon will be executed whenever the BOOLEAN_EXPRESSION is true.

Here is an example:

food = 'spam'

if food == 'spam':
    print['Ummmm, my favorite!']
    print['I feel like saying it 100 times...']
    print[100 * [food + '! ']]

The boolean expression after the if statement is called the condition. If it is true, then all the indented statements get executed. What happens if the condition is false, and food is not equal to 'spam'? In a simple if statement like this, nothing happens, and the program continues on to the next statement.

Run this example code and see what happens. Then change the value of food to something other than 'spam' and run it again, confirming that you don’t get any output.

Flowchart of an if statement

As with the for statement from the last chapter, the if statement is a compound statement. Compound statements consist of a header line and a body. The header line of the if statement begins with the keyword if followed by a boolean expression and ends with a colon [:].

The indented statements that follow are called a block. The first unindented statement marks the end of the block. Each statement inside the block must have the same indentation.

Indentation and the PEP 8 Python Style Guide

The Python community has developed a Style Guide for Python Code, usually referred to simply as “PEP 8”. The Python Enhancement Proposals, or PEPs, are part of the process the Python community uses to discuss and adopt changes to the language.

PEP 8 recommends the use of 4 spaces per indentation level. We will follow this [and the other PEP 8 recommendations] in this book.

To help us learn to write well styled Python code, there is a program called pep8 that works as an automatic style guide checker for Python source code. pep8 is installable as a package on Debian based GNU/Linux systems like Ubuntu.

In the Vim section of the appendix, Configuring Ubuntu for Python Web Development, there is instruction on configuring vim to run pep8 on your source code with the push of a button.

4.1.2. The if else statement¶

It is frequently the case that you want one thing to happen when a condition it true, and something else to happen when it is false. For that we have the if else statement.

if food == 'spam':
    print['Ummmm, my favorite!']
else:
    print["No, I won't have it. I want spam!"]

Here, the first print statement will execute if food is equal to 'spam', and the print statement indented under the else clause will get executed when it is not.

Flowchart of a if else statement

The syntax for an if else statement looks like this:

if BOOLEAN EXPRESSION:
    STATEMENTS_1        # executed if condition evaluates to True
else:
    STATEMENTS_2        # executed if condition evaluates to False

Each statement inside the if block of an if else statement is executed in order if the boolean expression evaluates to True. The entire block of statements is skipped if the boolean expression evaluates to False, and instead all the statements under the else clause are executed.

There is no limit on the number of statements that can appear under the two clauses of an if else statement, but there has to be at least one statement in each block. Occasionally, it is useful to have a section with no statements [usually as a place keeper, or scaffolding, for code you haven’t written yet]. In that case, you can use the pass statement, which does nothing except act as a placeholder.

if True:          # This is always true
    pass          # so this is always executed, but it does nothing
else:
    pass

Python terminology

Python documentation sometimes uses the term suite of statements to mean what we have called a block here. They mean the same thing, and since most other languages and computer scientists use the word block, we’ll stick with that.

Notice too that else is not a statement. The if statement has two clauses, one of which is the [optional] else clause. The Python documentation calls both forms, together with the next form we are about to meet, the if statement.

4.2. Chained conditionals¶

Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional:

if x  y:
    STATEMENTS_B
else:
    STATEMENTS_C

Flowchart of this chained conditional

elif is an abbreviation of else if. Again, exactly one branch will be executed. There is no limit of the number of elif statements but only a single [and optional] final else statement is allowed and it must be the last branch in the statement:

if choice == 'a':
    print["You chose 'a'."]
elif choice == 'b':
    print["You chose 'b'."]
elif choice == 'c':
    print["You chose 'c'."]
else:
    print["Invalid choice."]

Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes.

4.3. Nested conditionals¶

One conditional can also be nested within another. [It is the same theme of composibility, again!] We could have written the previous example as follows:

Flowchart of this nested conditional

if x  y:
        STATEMENTS_B
    else:
        STATEMENTS_C

The outer conditional contains two branches. The second branch contains another if statement, which has two branches of its own. Those two branches could contain conditional statements as well.

Although the indentation of the statements makes the structure apparent, nested conditionals very quickly become difficult to read. In general, it is a good idea to avoid them when you can.

Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:

if 0  for i in range[5]:
...     print['i is now:', i]
...
i is now 0
i is now 1
i is now 2
i is now 3
i is now 4
>>>

4.6. Tables¶

One of the things loops are good for is generating tables. Before computers were readily available, people had to calculate logarithms, sines and cosines, and other mathematical functions by hand. To make that easier, mathematics books contained long tables listing the values of these functions. Creating the tables was slow and boring, and they tended to be full of errors.

When computers appeared on the scene, one of the initial reactions was, “This is great! We can use the computers to generate the tables, so there will be no errors.” That turned out to be true [mostly] but shortsighted. Soon thereafter, computers and calculators were so pervasive that the tables became obsolete.

Well, almost. For some operations, computers use tables of values to get an approximate answer and then perform computations to improve the approximation. In some cases, there have been errors in the underlying tables, most famously in the table the Intel Pentium processor chip used to perform floating-point division.

Although a log table is not as useful as it once was, it still makes a good example. The following program outputs a sequence of values in the left column and 2 raised to the power of that value in the right column:

for x in range[13]:   # Generate numbers 0 to 12
    print[x, '\t', 2**x]

Using the tab character ['\t'] makes the output align nicely.

0       1
1       2
2       4
3       8
4       16
5       32
6       64
7       128
8       256
9       512
10      1024
11      2048
12      4096

4.7. The while statement¶

The general syntax for the while statement looks like this:

while BOOLEAN_EXPRESSION:
    STATEMENTS

Like the branching statements and the for loop, the while statement is a compound statement consisting of a header and a body. A while loop executes an unknown number of times, as long at the BOOLEAN EXPRESSION is true.

Here is a simple example:

number = 0
prompt = "What is the meaning of life, the universe, and everything? "

while number != "42":
    number =  input[prompt]

Notice that if number is set to 42 on the first line, the body of the while statement will not execute at all.

Here is a more elaborate example program demonstrating the use of the while statement

name = 'Harrison'
guess = input["So I'm thinking of person's name. Try to guess it: "]
pos = 0

while guess != name and pos >> count = 0
>>> count += 1
>>> count
1
>>> count += 1
>>> count
2

count += 1 is an abreviation for count = count + 1 . We pronouce the operator as “plus-equals”. The increment value does not have to be 1:

>>> n = 2
>>> n += 5
>>> n
7

There are similar abbreviations for -=, *=, /=, //= and %=:

>>> n = 2
>>> n *= 5
>>> n
10
>>> n -= 4
>>> n
6
>>> n //= 2
>>> n
3
>>> n %= 2
>>> n
1

4.11. Another while example: Guessing game¶

The following program implements a simple guessing game:

import random                      # Import the random module 

number = random.randrange[1, 1000] # Get random number between [1 and 1000]
guesses = 0
guess = int[input["Guess my number between 1 and 1000: "]]

while guess != number:
    guesses += 1
    if guess > number:
        print[guess, "is too high."] 
    elif guess  b, a < b, or a == b].

4.12. The break statement¶

The break statement is used to immediately leave the body of its loop. The next statement to be executed is the first one after the body:

for i in [12, 16, 17, 24, 29]:
    if i % 2 == 1:  # if the number is odd
        break        # immediately exit the loop
    print[i]
print["done"]

This prints:

4.13. The continue statement¶

This is a control flow statement that causes the program to immediately skip the processing of the rest of the body of the loop, for the current iteration. But the loop still carries on running for its remaining iterations:

for i in [12, 16, 17, 24, 29, 30]:
    if i % 2 == 1:      # if the number is odd
        continue        # don't process it
    print[i]
print["done"]

This prints:

4.14. Another for example¶

Here is an example that combines several of the things we have learned:

sentence = input['Please enter a sentence: ']
no_spaces = ''

for letter in sentence:
    if letter != ' ':
        no_spaces += letter

print["You sentence with spaces removed:"]
print[no_spaces]

Trace this program and make sure you feel confident you understand how it works.

4.15. Nested Loops for Nested Data¶

Now we’ll come up with an even more adventurous list of structured data. In this case, we have a list of students. Each student has a name which is paired up with another list of subjects that they are enrolled for:

students = [["Alejandro", ["CompSci", "Physics"]],
            ["Justin", ["Math", "CompSci", "Stats"]],
            ["Ed", ["CompSci", "Accounting", "Economics"]],
            ["Margot", ["InfSys", "Accounting", "Economics", "CommLaw"]],
            ["Peter", ["Sociology", "Economics", "Law", "Stats", "Music"]]]

Here we’ve assigned a list of five elements to the variable students. Let’s print out each student name, and the number of subjects they are enrolled for:

# print all students with a count of their courses.
for [name, subjects] in students:
    print[name, "takes", len[subjects], "courses"]

Python agreeably responds with the following output:

Aljandro takes 2 courses
Justin takes 3 courses
Ed takes 4 courses
Margot takes 4 courses
Peter takes 5 courses

Now we’d like to ask how many students are taking CompSci. This needs a counter, and for each student we need a second loop that tests each of the subjects in turn:

# Count how many students are taking CompSci
counter = 0
for [name, subjects] in students:
    for s in subjects:                 # a nested loop!
        if s == "CompSci":
            counter += 1

print["The number of students taking CompSci is", counter]

The number of students taking CompSci is 3

You should set up a list of your own data that interests you — perhaps a list of your CDs, each containing a list of song titles on the CD, or a list of movie titles, each with a list of movie stars who acted in the movie. You could then ask questions like “Which movies starred Angelina Jolie?”

4.16. List comprehensions¶

A list comprehension is a syntactic construct that enables lists to be created from other lists using a compact, mathematical syntax:

>>> numbers = [1, 2, 3, 4]
>>> [x**2 for x in numbers]
[1, 4, 9, 16]
>>> [x**2 for x in numbers if x**2 > 8]
[9, 16]
>>> [[x, x**2, x**3] for x in numbers]
[[1, 1, 1], [2, 4, 8], [3, 9, 27], [4, 16, 64]]
>>> files = ['bin', 'Data', 'Desktop', '.bashrc', '.ssh', '.vimrc']
>>> [name for name in files if name[0] != '.']
['bin', 'Data', 'Desktop']
>>> letters = ['a', 'b', 'c']
>>> [n * letter for n in numbers for letter in letters]
['a', 'b', 'c', 'aa', 'bb', 'cc', 'aaa', 'bbb', 'ccc', 'aaaa', 'bbbb', 'cccc']
>>>

The general syntax for a list comprehension expression is:

[expr for  item1 in  seq1 for item2 in seq2 ... for itemx in seqx if condition]

This list expression has the same effect as:

output_sequence = []
for item1 in seq1:
    for item2 in seq2:
        ...
            for itemx in seqx:
                if condition:
                    output_sequence.append[expr]

As you can see, the list comprehension is much more compact.

4.17. Glossary¶

append

To add new data to the end of a file or other data object.

block

A group of consecutive statements with the same indentation.

body

The block of statements in a compound statement that follows the header.

branch

One of the possible paths of the flow of execution determined by conditional execution.

chained conditional

A conditional branch with more than two possible flows of execution. In Python chained conditionals are written with if ... elif ... else statements.

compound statement

A Python statement that has two parts: a header and a body. The header begins with a keyword and ends with a colon [:]. The body contains a series of other Python statements, all indented the same amount.

Note

We will use the Python standard of 4 spaces for each level of indentation.

condition

The boolean expression in a conditional statement that determines which branch is executed.

conditional statement

A statement that controls the flow of execution depending on some condition. In Python the keywords if, elif, and else are used for conditional statements.

counter

A variable used to count something, usually initialized to zero and incremented in the body of a loop.

cursor

An invisible marker that keeps track of where the next character will be printed.

decrement

Decrease by 1.

definite iteration

A loop where we have an upper bound on the number of times the body will be executed. Definite iteration is usually best coded as a for loop.

delimiter

A sequence of one or more characters used to specify the boundary between separate parts of text.

increment

Both as a noun and as a verb, increment means to increase by 1.

infinite loop

A loop in which the terminating condition is never satisfied.

indefinite iteration

A loop where we just need to keep going until some condition is met. A while statement is used for this case.

initialization [of a variable]

To initialize a variable is to give it an initial value. Since in Python variables don’t exist until they are assigned values, they are initialized when they are created. In other programming languages this is not the case, and variables can be created without being initialized, in which case they have either default or garbage values.

iteration

Repeated execution of a set of programming statements.

loop

A statement or group of statements that execute repeatedly until a terminating condition is satisfied.

loop variable

A variable used as part of the terminating condition of a loop.

nested loop

A loop inside the body of another loop.

nesting

One program structure within another, such as a conditional statement inside a branch of another conditional statement.

newline

A special character that causes the cursor to move to the beginning of the next line.

prompt

A visual cue that tells the user to input data.

reassignment

Making more than one assignment to the same variable during the execution of a program.

tab

A special character that causes the cursor to move to the next tab stop on the current line.

trichotomy

Given any real numbers a and b, exactly one of the following relations holds: a < b, a > b, or a == b. Thus when you can establish that two of the relations are false, you can assume the remaining one is true.

trace

To follow the flow of execution of a program by hand, recording the change of state of the variables and any output produced.

What is iterative control statements in Python?

In Python, the iterative statements are also known as looping statements or repetitive statements. The iterative statements are used to execute a part of the program repeatedly as long as a given condition is True.

What is a condition

CONCEPT: A condition-controlled loop causes a statement or set of statements to repeat as long as a condition is true. In Python you use the while statement to write a condition-controlled loop. The while loop gets its name from the way it works: while a condition is true, do some task.

Which statements are used to implement iteration in Python?

Python has two statements for iteration – the for statement, which we met last chapter, and the while statement.

What is condition

Condition-controlled iteration repeatedly executes a section of code until a condition is met - or no longer met. The two most common types of condition-controlled iteration are: while loops, which use the statements WHILE and END WHILE. repeat loops, which use the statements REPEAT and UNTIL.

Chủ Đề