SlideShare a Scribd company logo
Chapter 3: Control Structures
In Chapter 2 we looked at the “nuts and bolts” of programming. In this chapter, we discuss
the three fundamental means of controlling the order of execution of instructions within a
program, referred to as sequential, selection, and iterative control.
1
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons
The first electronic computers over sixty years ago were referred to as
“Electronic Brains.” This gave the misleading impression that computers could
“think.” Although very complex in their design, computers are machines that
simply do, step-by-step (instruction-by-instruction), what they are told. Thus,
there is no more intelligence in a computer than what it is instructed to do.
What computers can do, however, is to execute a series of instructions very
quickly and very reliably. It is the speed in which instructions can be executed
that gives computers their power (see Figure 3-1), since the execution of many
simple instructions can result in very complex behavior. And thus this is the
enticement of computing. A computer can accomplish any task there is an
algorithm for. The instructions could be for something as simple as sorting lists,
or as ambitious as performing intelligent tasks that as of now only humans are
capable of performing.
In this chapter, we look at how to control the sequence of instructions that are
executed in Python.
2
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons
Motivation
3
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons
Control flow is the order that instructions are executed in a program. A
control statement is a statement that determines control flow of a set of
instructions.
There are three fundamental forms of control that programming
languages provide,
• sequential control
• selection control
• iterative control
4
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.1 What is a Control Structure?
What is a Control Structure?
5
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.1 What is a Control Structure?
The Boolean data type contains two Boolean values, denoted as True
and False in Python.
A Boolean expression is an expression that evaluates to a Boolean value.
Boolean expressions are used to denote the conditions for selection and
iterative control statements.
6
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
Boolean Expressions
Relational Operators
The relational operators in Python perform the usual comparison
operations.
Relational expressions are a type of Boolean expression, since they
evaluate to a Boolean result.
7
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
8
Relational Operators in Python
Note that these operators not only apply to numeric values, but to any
set of values that has an ordering, such as strings.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
Let’s Try It
9
What do each of the following relational expressions evaluate
to?
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
Membership Operators
Python provides a convenient pair of membership operators. These
operators can be used to easily determine if a particular value occurs
within a specified list of values.
10
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
The membership operators can also be used to check if a given string
occurs within another string,
>>> 'Dr.' in 'Dr. Madison'
True
As with the relational operators, the membership operators can be used
to construct Boolean expressions.
11
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
Let’s Try It
12
What do each of the following relational expressions evaluate
to?
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
Boolean Operators
George Boole, in the mid-1800s, developed what we now call Boolean
algebra. His goal was to develop an algebra based on true/false rather
than numerical values.
Boolean algebra contains a set of Boolean (logical) operators, denoted
by and, or, and not. These logical operators can be used to construct
arbitrarily complex Boolean expressions.
13
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
14
Logical and is true only when both its operands are true—otherwise, it is
false. Logical or is true when either or both of its operands are true, and
thus false only when both operands are false. Logical not simply reverses
truth values—not False equals True, and not True equals False.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
15
Consider the following :
1 <= num <= 10
Although in mathematics this notation is understood, consider how this
would be evaluated in a programming language (for num equal to 15):
1 <= num <= 10  1 <= 15 <= 10  True <= 10  ?!?
The subexpression for the left relational operator would be evaluated
first, which evaluates to True. Continuing, however, it doesn’t make
sense to check if True is less than or equal to 10. Some programming
languages would generate a mixed-type expression error for this.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
16
Therefore, the correct way for computer evaluation of the condition is
by use of the Boolean and operator (again for num equal to 15):
1<=num andnum<=10  (1<=num) and (num<=10) 
True and (num<=10)  True and True  True
Let’s see what we get when we do evaluate the expression in the Python
shell (for num equal to 15)
>>> 1<=num andnum<=10
False
We actually get the correct result, False. If we were to try the original
form of the expression:
>>> 1<= num <=10
False
This also works without error in Python?!
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
17
What you need to be aware of is that Python allows a relational
expression of the form,
1<= num <=10
but and automatically converts it to the form before evaluated,
1<=num andnum<=10
Thus, although Python offers this convenient shorthand, many
programming languages require the longer form expression by use of
logical and, and would give an error (or incorrect results) if written in the
shorter form. Thus, as a novice programmer, it would be best not to get
in the habit of using the shorter form expression particular to Python.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
Let’s Try It
18
What do each of the following relational expressions evaluate
to?
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
Operator Precedence and Boolean
Expressions
George Boole, in the mid-1800s, developed what we now call Boolean
algebra. His goal was to develop an algebra based on true/false rather
than numerical values.
Boolean algebra contains a set of Boolean (logical) operators, denoted
by and, or, and not. These logical operators can be used to construct
arbitrarily complex Boolean expressions.
19
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
20
Operator Precedence and Boolean Expressions
As we saw earlier, in the table, high-priority operators are placed before
lower-priority operators. Thus we see that all arithmetic operators are
performed before any relational or Boolean operators.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
21
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
Unary Boolean operator not has higher precedence then and, and
Boolean operator and has higher precedence than the or operator.
22
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
As with arithmetic expressions, it is good programming practice to use
parentheses, even if not needed, to add clarity and enhance readability,
If not all subexpressions,
Let’s Try It
23
From the Python shell, enter the following and observe the
results.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
Short-Circuit Evaluation
There are differences in how Boolean expressions are evaluated in
different programming languages. For logical and, if the first operand
evaluates to false, then regardless of the value of the second operand,
the expression is false. Similarly, for logical or, if the first operand
evaluates to true, regardless of the value of the second operand, the
expression is true.
Because of this, some programming languages do not evaluate the
second operand when the result is known by the first operand alone,
called short-circuit (lazy) evaluation.
24
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
Subtle errors can result if the programmer is not aware of this. For
example, the expression
25
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
would evaluate without error for all values of n when short-circuit
evaluation is used. If programming in a language not using short-circuit
evaluation, however, a “divide by zero” error would result when n is
equal to 0. In such cases, the proper construction would be,
In the Python programming language, short-circuit evaluation is used.
Logically Equivalent
Boolean Expressions
In numerical algebra, there are arithmetically equivalent expressions of
different form.
For example, x(y + z) and xy + xz are equivalent for any numerical values
x, y, and z. Similarly, there are logically equivalent Boolean expressions
of different form.
26
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
Logically equivalent Boolean expressions of different form.
Fundamental logically equivalent Boolean expressions.
The last two equivalences are referred to as De Morgan’s Laws.
Let’s Try It
29
From the Python shell, enter the following and observe the
results.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
30
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
31
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
32
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
33
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
34
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
35
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
36
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
37
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
A selection control statement is a control statement providing selective
execution of instructions. A selection control structure is a given set of
instructions and the selection control statement(s) controlling their
execution. Next, the if statement provides selection control in Python.
38
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
Selection Control
If Statement
An if statement is a selection control statement based on the value of a
given Boolean expression.
39
Note that if statements may omit the “else” part.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
Below is a version of the temperature conversion program that allows
the user to select a conversion of Fahrenheit to Celsius, or Celsius to
Fahrenheit, implemented by the use of an if statement.
40
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
Indentation in Python
One fairly unique aspect of Python is that the amount of indentation of
each program line is significant. In most programming languages,
indentation has no affect on program logic—it is simply used to align
program lines to aid readability. In Python, however, indentation is used
to associate and group statements.
41
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
A header in Python is a specific keyword followed by a colon. In the
example, the if-else statement contains two headers, “if which 5 = 'F':”
containing keyword if, and “else:” consisting only of the keyword else.
Headers that are part of the same compound statement must be
indented the same amount—otherwise, a syntax error will result.
42
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
The set of statements following a header in Python is called a suite
(commonly called a block ). The statements of a given suite must all be
indented the same amount. A header and its associated suite are
together referred to as a clause.
A compound statement in Python may consist of one or more clauses.
While four spaces is commonly used for each level of indentation, any
number of spaces may be used, as shown below.
43
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
Let’s Try It
44
From IDLE, create and run a Python program containing the
code on the left and observe the results. Modify and run the
code to match the version on the right and again observe the
results. Make sure to indent the code exactly as shown.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
Multi-Way Selection
Python provides two means of constructing multi-way selection—one
involving multiple nested if statements, and the other involving a single
if statement and the use of elif headers.
45
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
46
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
Multi-Way Selection by Use of Nested If Statements
Below is a version of the temperature conversion program that checks
for invalid input, implemented by the use of nested if statements.
47
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
Let’s Try It
48
From IDLE, create and run a simple program containing the
code below and observe the results. Make sure to indent the
code exactly as shown.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
49
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
Multi-Way Selection by Use of elif Header
Let’s Try It
50
From IDLE, create and run a Python program containing the
code below and observe the results. Make sure to indent the
code exactly as shown.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
The following Python program (Figure 3-16) prompts the user for a given
month (and year for February), and displays how many days are in the
month. This program utilizes the following programming features:
➤ if statement ➤ elif header
51
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.1 Literals
Number of Days in Month Program
Let’s Apply It
52
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.1 Literals
53
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.1 Literals
On line 7 , variable
valid_input is initialized
to True for input error-
checking. Line 10
prompts the user for the
month (1–12), stored in
variable month. On line
15 the month of
February is checked for.
Line 24 checks if month
is equal to 1, 3, 5, 7, 8,
10, or 12. If true, then
num_days is assigned to
31. If not true, line 28
checks if month is equal
to 4, 6, 9, or 11. If true,
num_days is assigned to
30. If not true, then an
invalid month value was
entered, and valid_input
is set to False.
Finally, the number of
days in the month is
displayed
only if the input is valid (
line 38 ).
54
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
55
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
56
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
57
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
58
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
59
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
An iterative control statement is a control statement providing the
repeated execution of a set of instructions. An iterative control structure
is a set of instructions and the iterative control statement(s) controlling
their execution. Because of their repeated execution, iterative control
structures are commonly referred to as “loops.” We look at one specific
iterative control statement next: the while statement.
60
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
Iterative Control
While Statement
A while statement is an iterative control statement that repeatedly
executes a set of statements based on a provided Boolean expression
(condition). All iterative control needed in a program can be achieved by
use of the while statement.
61
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
As long as the condition of a while statement is true, the statements
within the loop are (re)executed. Once the condition becomes false, the
iteration terminates and control continues with the first statement after
the while loop.
Note that it is possible that the first time a loop is reached, the condition
may be false, and therefore the loop would never be executed.
62
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
Execution steps for adding the first three integers by use of the previous
while loop.
63
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
Input Error Checking
The while statement is well suited for input error checking in a program.
This is demonstrated in the revised version of the temperature
conversion program.
64
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
The while loop is used to force the user to re-enter if neither an ‘F’ (for
conversion to Fahrenheit) or a ‘C’ (for conversion to Celsius) is not
entered.
65
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
Let’s Try It
66
In IDLE, create and run a simple program containing the code
below and observe the results. Make sure to indent the code
exactly as shown.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
Infinite Loops
An infinite loop is an iterative control structure that never terminates
(or eventually terminates with a system error). Infinite loops are
generally the result of programming errors. For example, if the condition
of a while loop can never be false, an infinite loop will result when
executed.
67
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
Following is an example program containing an infinite loop.
68
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
The while loop is an infinite loop (for any value of n 1 or greater)
because the value of current is not incremented.
Let’s Try It
69
From IDLE, create and run a simple program containing the
code below and observe the results. Indent the code exactly
as shown. To terminate an executing loop, hit ctrl-C.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
Definite vs. Indefinite Loops
A definite loop is a program loop in which the number of times the loop
will iterate can be determined before the loop is executed. Following is
an example of a definite loop.
70
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
Although it is not known what the value of n will be until the input
statement is executed, its value is known by the time the while loop is
reached. Thus, it will execute “n times.”
An indefinite loop is a program loop in which the number of times that
the loop will iterate cannot be determined before the loop is executed.
71
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
In this case, the number of times that the loop will be executed depends
on how many times the user mistypes the input.
Boolean Flags and Indefinite Loops
Often the condition of a given while loop is denoted by a single Boolean
variable, called a Boolean flag.
72
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
Boolean variable valid_entries on line 12 in the following program
is an example of the use of a Boolean flag for controlling a while loop.
73
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
The following program implements an exercise for children learning to count
change. It displays a random value between 1 and 99 cents, and asks the
user to enter a set of coins that sums exactly to the amount shown. The
program utilizes the following programming features:
➤ while loop ➤ if statement ➤ Boolean flag
➤ random number generator
74
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.1 Literals
Coin Change Exercise Program
Let’s Apply It
75
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.1 Literals
76
Introduction to Computer Science Using Python – Dierbach Copyright 2013 JohnWiley and Sons Section 2.1 Literals
On line 18, function randint (imported on
line 3) is called to randomly generate a coin
value for the user to match, stored in variable
amount. On line 13 Boolean variable
terminate is initialized to False, used to
determine when the program terminates.
The game begins on line 17. The while loop is
re-executed for each new game played (while
terminate is False). The while loop on
line 23 is re-executed while the current game
is still in play (while game_over is false).
The game ends when either the user enters a
blank line, in which case the result is
displayed and game_over is set to True
(lines 37–43), or if the total amount exceeds
the amount to be matched On line 26, a
third Boolean flag is used, valid_entry,
for controlling whether the user should be
prompted again because of invalid input (on
lines 45–48 ).
Note the use of membership operator in
(line 32).
77
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
78
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
79
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
80
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
81
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
82
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
83
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
84
We look at the problem of displaying a given calendar month.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Calendar Month Program
Calendar Month
The Problem
85
The problem is to display a calendar month for any given month between
January 1800 and December 2099. The format of the month should be as
shown.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Calendar Month
Problem Analysis
86
Two specific algorithms are needed for this problem.
First, we need an algorithm for computing the first day of a given month for
years 1800 through 2099. This algorithm is given in Chapter 1.
The second needed algorithm is for appropriately displaying the calendar
month, given the day of the week that the first day falls on, and the number
of days in the month. We shall develop this algorithm. The data
representation issues for this problem are straightforward.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Calendar Month
Program Design
87
Meeting the Program Requirements
We will develop and implement an algorithm that displays the month as given. There
is no requirement of how the month and year are to be entered. We shall therefore
request the user to enter the month and year as integer values, with appropriate
input error checking.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Calendar Month
Program Design
88
Data Description
What needs to be represented is the month and year entered, whether the year is a
leap year, the number of days in the month, and which day the first of the month falls
on. Given that information, the calendar month can be displayed. The year and
month will be entered and stored as integer values, represented by variables year and
month,
year = 2012 month = 5
The remaining values will be computed by the program based on the given year and
month, as given below,
leap_year num_days_in_month day_of_week
Variable leap_year holds a Boolean (True/False) value. Variables num_days_
in_month and day_of_week each hold integer values.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
89
Algorithmic Approach
Algorithm for computing the day of the week. Have an algorithm for this.
Recall that the result of this algorithm is a value between 0-6 indicating the day of the
week that a given date falls on.
For this program, we need only determine the day of the week for the first of the
month. All the following days follow, for the given number of days in the month.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
90
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
The Overall Steps of the Program
Calendar Month
Program Implementation
91
• Prompts user for month and year. Validates that value entered for month
correct (1-12), and that year entered is in the range 1800-2099, inclusive.
• Determines whether the year is a leap year. Also determines the number of
days in the month.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Stage 1—Input Validation /
Determining Leap Years and Number of Days in Month
92
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
93
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Stage 1 Testing
We add test statements that displays the number of days in the month, and
whether the year is a leap year or not. The test run below indicates that
these values are correct for the given month and year.
94
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
A Set of Test Cases
Program Implementation
95
Stage 2 of the program includes the code for determining the day of the
week for the first day of a given month and year, with a final print statement
displaying the test results.
Note that for testing purposes, there is no need to convert the day number
into the actual name (e.g., “Monday”)—this “raw output” is good enough.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Stage 2—Determining the Day of the Week
96
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
97
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
98
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Stage 2 Testing
Following is the output of a test run of the program. The day of the week
value displayed is 1 (Sunday) which is the correct day of the week for the date
entered.
99
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
A Set of Test Cases for Stage 2 Testing
Program Implementation
100
In the final stage of the program we add the code for displaying a calendar
month.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Final Stage – Displaying the Calendar Month
101
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
102
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
103
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
104
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
105
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
106
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Stage 2 Testing
Following is the output of a test run of the program.
The month displayed is obviously incorrect, since each week is displayed with
eight days! The testing of all other months produces the same results.
Since the first two stages of the program were successfully tested, the problem
must be in the code added in the final stage.
107
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Lines 128–129 is where the column is reset back to column 1 and a new screen line is
started, based on the current value of variable current_col,
108
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Variable starting_col is set to the value (0-6) for the day of the week for the
particular month being displayed. Variable current_col is initialized to 1 at line
108 , and is advanced to the proper starting column on lines 113–115 .
109
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Since the day of the week results have been successfully tested, we can assume that
current_col will have a value between 0 and 6. With that assumption, we can
step though lines 125–129 and see if this is where the problem is.
110
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Lines 128–129 is where the column is reset back to column 1 and a new screen line is
started, based on the current value of variable current_col,
if current_col <= 7:
current_col = current_col + 1
else:
current_col + 1
print()
Now it is clear what the problem is—the classic “off by one” error! The condition of
the while loop should be current_col < 7, not current_col <= 7.
Current_col should be reset to 1 once the seventh column has been displayed
(when current_col is 7). Using the <= operator causes current_col to be reset to 1
only after an eighth column is displayed.
Deskchecking the Program Segment
We check what happens as the value of current_col approaches 7. Stepping
through a program on paper is referred to as deskchecking.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program 111
Although the column error has been corrected, we find that the first of the month
appears under the wrong column! The month should start on a Wednesday (fourth
column), not a Thursday column (fifth column).
After re-executing the program with this correction we get the following output.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program 112
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program 113
Other months are tested, each found to be off by one day. We therefore look at
lines 113–115 that are responsible for moving over the cursor to the correct
starting column,
while current_col <= starting_col:
print(blank_column, end = '')
current_col = current_col + 1
We consider whether there is another “off by one” error. Reconsidering the
condition of the while loop, we realize that, in fact, this is the error. If the correct
starting column is 4 (Wednesday), then the cursor should move past three
columns and place a 1 in the fourth column. The current condition, however,
would move the cursor past four columns, thus placing a 1 in the fifth column
(Thursday). The corrected code is
while current_col < starting_col:
print(' ', end = '')
current_col = current_col + 1
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program 114
The month is now correctly displayed. We complete the testing by executing the
program on a set of test cases.
Ad

Recommended

UNIT - 2 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
UNIT - 2 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
Nandakumar P
 
An Introduction to Computer Science with Java, Python an.docx
An Introduction to Computer Science with Java, Python an.docx
daniahendric
 
Lecture 07.pptx
Lecture 07.pptx
Mohammad Hassan
 
Python-Certification-Training-Day-1-2.pptx
Python-Certification-Training-Day-1-2.pptx
muzammildev46gmailco
 
Brixton Library Technology Initiative Week1 Recap
Brixton Library Technology Initiative Week1 Recap
Basil Bibi
 
Python Programming
Python Programming
Sreedhar Chowdam
 
Python Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdf
Sreedhar Chowdam
 
An Introduction : Python
An Introduction : Python
Raghu Kumar
 
Lecture 1 .
Lecture 1 .
SwatiHans10
 
Introduction to programming with python
Introduction to programming with python
Porimol Chandro
 
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Edureka!
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
practical file 11.pdf
practical file 11.pdf
PanditKavyaKaushik
 
Python.pptx
Python.pptx
AKANSHAMITTAL2K21AFI
 
Functional programming in Python 1st Edition David Mertz
Functional programming in Python 1st Edition David Mertz
nkossivilana87
 
Python for Scientific Computing
Python for Scientific Computing
Albert DeFusco
 
23CSC101T PSPP python programming - UNIT 3.pdf
23CSC101T PSPP python programming - UNIT 3.pdf
RajeshThanikachalam
 
23CSC101T PSPP python program - UNIT 3.pdf
23CSC101T PSPP python program - UNIT 3.pdf
RajeshThanikachalam
 
Python programming
Python programming
saroja20
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
DhivyaSubramaniyam
 
1. PGA2.0-Python Programming-Intro to Python.pptx
1. PGA2.0-Python Programming-Intro to Python.pptx
Rakesh Ahuja
 
Boolean and conditional logic in Python
Boolean and conditional logic in Python
gsdhindsa
 
Python Control structures
Python Control structures
Siddique Ibrahim
 
Python notes for students to develop and learn
Python notes for students to develop and learn
kavithaadhilakshmi
 
Introduction to Python Language and Data Types
Introduction to Python Language and Data Types
Ravi Shankar
 
Python for informatics
Python for informatics
Christoforos Rekatsinas
 
PYthon
PYthon
Rajesh Tiwary
 
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion |
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion |
FabMinds
 
Logical Design Architecture in Internet of Things
Logical Design Architecture in Internet of Things
Senthil Vit
 
Wireless sensor networks in Internet of Things
Wireless sensor networks in Internet of Things
Senthil Vit
 

More Related Content

Similar to Control structures in Python programming (20)

Lecture 1 .
Lecture 1 .
SwatiHans10
 
Introduction to programming with python
Introduction to programming with python
Porimol Chandro
 
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Edureka!
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
practical file 11.pdf
practical file 11.pdf
PanditKavyaKaushik
 
Python.pptx
Python.pptx
AKANSHAMITTAL2K21AFI
 
Functional programming in Python 1st Edition David Mertz
Functional programming in Python 1st Edition David Mertz
nkossivilana87
 
Python for Scientific Computing
Python for Scientific Computing
Albert DeFusco
 
23CSC101T PSPP python programming - UNIT 3.pdf
23CSC101T PSPP python programming - UNIT 3.pdf
RajeshThanikachalam
 
23CSC101T PSPP python program - UNIT 3.pdf
23CSC101T PSPP python program - UNIT 3.pdf
RajeshThanikachalam
 
Python programming
Python programming
saroja20
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
DhivyaSubramaniyam
 
1. PGA2.0-Python Programming-Intro to Python.pptx
1. PGA2.0-Python Programming-Intro to Python.pptx
Rakesh Ahuja
 
Boolean and conditional logic in Python
Boolean and conditional logic in Python
gsdhindsa
 
Python Control structures
Python Control structures
Siddique Ibrahim
 
Python notes for students to develop and learn
Python notes for students to develop and learn
kavithaadhilakshmi
 
Introduction to Python Language and Data Types
Introduction to Python Language and Data Types
Ravi Shankar
 
Python for informatics
Python for informatics
Christoforos Rekatsinas
 
PYthon
PYthon
Rajesh Tiwary
 
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion |
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion |
FabMinds
 
Introduction to programming with python
Introduction to programming with python
Porimol Chandro
 
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Edureka!
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
Functional programming in Python 1st Edition David Mertz
Functional programming in Python 1st Edition David Mertz
nkossivilana87
 
Python for Scientific Computing
Python for Scientific Computing
Albert DeFusco
 
23CSC101T PSPP python programming - UNIT 3.pdf
23CSC101T PSPP python programming - UNIT 3.pdf
RajeshThanikachalam
 
23CSC101T PSPP python program - UNIT 3.pdf
23CSC101T PSPP python program - UNIT 3.pdf
RajeshThanikachalam
 
Python programming
Python programming
saroja20
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
DhivyaSubramaniyam
 
1. PGA2.0-Python Programming-Intro to Python.pptx
1. PGA2.0-Python Programming-Intro to Python.pptx
Rakesh Ahuja
 
Boolean and conditional logic in Python
Boolean and conditional logic in Python
gsdhindsa
 
Python notes for students to develop and learn
Python notes for students to develop and learn
kavithaadhilakshmi
 
Introduction to Python Language and Data Types
Introduction to Python Language and Data Types
Ravi Shankar
 
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion |
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion |
FabMinds
 

More from Senthil Vit (20)

Logical Design Architecture in Internet of Things
Logical Design Architecture in Internet of Things
Senthil Vit
 
Wireless sensor networks in Internet of Things
Wireless sensor networks in Internet of Things
Senthil Vit
 
Classification Algorithm in Machine Learning
Classification Algorithm in Machine Learning
Senthil Vit
 
Decision Trees Learning in Machine Learning
Decision Trees Learning in Machine Learning
Senthil Vit
 
Operating system Virtualization_NEW.pptx
Operating system Virtualization_NEW.pptx
Senthil Vit
 
Synchronization Peterson’s Solution.pptx
Synchronization Peterson’s Solution.pptx
Senthil Vit
 
Data and Expressions in Python programming
Data and Expressions in Python programming
Senthil Vit
 
Python programming Introduction about Python
Python programming Introduction about Python
Senthil Vit
 
Switching Problems.pdf
Switching Problems.pdf
Senthil Vit
 
Big Oh.ppt
Big Oh.ppt
Senthil Vit
 
AsymptoticNotations.ppt
AsymptoticNotations.ppt
Senthil Vit
 
snort.ppt
snort.ppt
Senthil Vit
 
First Best and Worst Fit.pptx
First Best and Worst Fit.pptx
Senthil Vit
 
File Implementation Problem.pptx
File Implementation Problem.pptx
Senthil Vit
 
Design Issues of an OS.ppt
Design Issues of an OS.ppt
Senthil Vit
 
Operating Systems – Structuring Methods.pptx
Operating Systems – Structuring Methods.pptx
Senthil Vit
 
deadlock.ppt
deadlock.ppt
Senthil Vit
 
Virtualization.pptx
Virtualization.pptx
Senthil Vit
 
Traffic-Monitoring.ppt
Traffic-Monitoring.ppt
Senthil Vit
 
Lect_2.pptx
Lect_2.pptx
Senthil Vit
 
Logical Design Architecture in Internet of Things
Logical Design Architecture in Internet of Things
Senthil Vit
 
Wireless sensor networks in Internet of Things
Wireless sensor networks in Internet of Things
Senthil Vit
 
Classification Algorithm in Machine Learning
Classification Algorithm in Machine Learning
Senthil Vit
 
Decision Trees Learning in Machine Learning
Decision Trees Learning in Machine Learning
Senthil Vit
 
Operating system Virtualization_NEW.pptx
Operating system Virtualization_NEW.pptx
Senthil Vit
 
Synchronization Peterson’s Solution.pptx
Synchronization Peterson’s Solution.pptx
Senthil Vit
 
Data and Expressions in Python programming
Data and Expressions in Python programming
Senthil Vit
 
Python programming Introduction about Python
Python programming Introduction about Python
Senthil Vit
 
Switching Problems.pdf
Switching Problems.pdf
Senthil Vit
 
AsymptoticNotations.ppt
AsymptoticNotations.ppt
Senthil Vit
 
First Best and Worst Fit.pptx
First Best and Worst Fit.pptx
Senthil Vit
 
File Implementation Problem.pptx
File Implementation Problem.pptx
Senthil Vit
 
Design Issues of an OS.ppt
Design Issues of an OS.ppt
Senthil Vit
 
Operating Systems – Structuring Methods.pptx
Operating Systems – Structuring Methods.pptx
Senthil Vit
 
Virtualization.pptx
Virtualization.pptx
Senthil Vit
 
Traffic-Monitoring.ppt
Traffic-Monitoring.ppt
Senthil Vit
 
Ad

Recently uploaded (20)

社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Fundamentals of Digital Design_Class_21st May - Copy.pptx
Fundamentals of Digital Design_Class_21st May - Copy.pptx
drdebarshi1993
 
NALCO Green Anode Plant,Compositions of CPC,Pitch
NALCO Green Anode Plant,Compositions of CPC,Pitch
arpitprachi123
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Engineering Mechanics Introduction and its Application
Engineering Mechanics Introduction and its Application
Sakthivel M
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
Water demand - Types , variations and WDS
Water demand - Types , variations and WDS
dhanashree78
 
Microwatt: Open Tiny Core, Big Possibilities
Microwatt: Open Tiny Core, Big Possibilities
IBM
 
Machine Learning - Classification Algorithms
Machine Learning - Classification Algorithms
resming1
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
Introduction to Natural Language Processing - Stages in NLP Pipeline, Challen...
Introduction to Natural Language Processing - Stages in NLP Pipeline, Challen...
resming1
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
ravicivil
 
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
gowthamvicky1
 
Cadastral Maps
Cadastral Maps
Google
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Fundamentals of Digital Design_Class_21st May - Copy.pptx
Fundamentals of Digital Design_Class_21st May - Copy.pptx
drdebarshi1993
 
NALCO Green Anode Plant,Compositions of CPC,Pitch
NALCO Green Anode Plant,Compositions of CPC,Pitch
arpitprachi123
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Engineering Mechanics Introduction and its Application
Engineering Mechanics Introduction and its Application
Sakthivel M
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
Water demand - Types , variations and WDS
Water demand - Types , variations and WDS
dhanashree78
 
Microwatt: Open Tiny Core, Big Possibilities
Microwatt: Open Tiny Core, Big Possibilities
IBM
 
Machine Learning - Classification Algorithms
Machine Learning - Classification Algorithms
resming1
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
Introduction to Natural Language Processing - Stages in NLP Pipeline, Challen...
Introduction to Natural Language Processing - Stages in NLP Pipeline, Challen...
resming1
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
ravicivil
 
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
gowthamvicky1
 
Cadastral Maps
Cadastral Maps
Google
 
Ad

Control structures in Python programming

  • 1. Chapter 3: Control Structures In Chapter 2 we looked at the “nuts and bolts” of programming. In this chapter, we discuss the three fundamental means of controlling the order of execution of instructions within a program, referred to as sequential, selection, and iterative control. 1 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons
  • 2. The first electronic computers over sixty years ago were referred to as “Electronic Brains.” This gave the misleading impression that computers could “think.” Although very complex in their design, computers are machines that simply do, step-by-step (instruction-by-instruction), what they are told. Thus, there is no more intelligence in a computer than what it is instructed to do. What computers can do, however, is to execute a series of instructions very quickly and very reliably. It is the speed in which instructions can be executed that gives computers their power (see Figure 3-1), since the execution of many simple instructions can result in very complex behavior. And thus this is the enticement of computing. A computer can accomplish any task there is an algorithm for. The instructions could be for something as simple as sorting lists, or as ambitious as performing intelligent tasks that as of now only humans are capable of performing. In this chapter, we look at how to control the sequence of instructions that are executed in Python. 2 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Motivation
  • 3. 3 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons
  • 4. Control flow is the order that instructions are executed in a program. A control statement is a statement that determines control flow of a set of instructions. There are three fundamental forms of control that programming languages provide, • sequential control • selection control • iterative control 4 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.1 What is a Control Structure? What is a Control Structure?
  • 5. 5 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.1 What is a Control Structure?
  • 6. The Boolean data type contains two Boolean values, denoted as True and False in Python. A Boolean expression is an expression that evaluates to a Boolean value. Boolean expressions are used to denote the conditions for selection and iterative control statements. 6 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions Boolean Expressions
  • 7. Relational Operators The relational operators in Python perform the usual comparison operations. Relational expressions are a type of Boolean expression, since they evaluate to a Boolean result. 7 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 8. 8 Relational Operators in Python Note that these operators not only apply to numeric values, but to any set of values that has an ordering, such as strings. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 9. Let’s Try It 9 What do each of the following relational expressions evaluate to? Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 10. Membership Operators Python provides a convenient pair of membership operators. These operators can be used to easily determine if a particular value occurs within a specified list of values. 10 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 11. The membership operators can also be used to check if a given string occurs within another string, >>> 'Dr.' in 'Dr. Madison' True As with the relational operators, the membership operators can be used to construct Boolean expressions. 11 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 12. Let’s Try It 12 What do each of the following relational expressions evaluate to? Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 13. Boolean Operators George Boole, in the mid-1800s, developed what we now call Boolean algebra. His goal was to develop an algebra based on true/false rather than numerical values. Boolean algebra contains a set of Boolean (logical) operators, denoted by and, or, and not. These logical operators can be used to construct arbitrarily complex Boolean expressions. 13 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 14. 14 Logical and is true only when both its operands are true—otherwise, it is false. Logical or is true when either or both of its operands are true, and thus false only when both operands are false. Logical not simply reverses truth values—not False equals True, and not True equals False. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 15. 15 Consider the following : 1 <= num <= 10 Although in mathematics this notation is understood, consider how this would be evaluated in a programming language (for num equal to 15): 1 <= num <= 10  1 <= 15 <= 10  True <= 10  ?!? The subexpression for the left relational operator would be evaluated first, which evaluates to True. Continuing, however, it doesn’t make sense to check if True is less than or equal to 10. Some programming languages would generate a mixed-type expression error for this. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 16. 16 Therefore, the correct way for computer evaluation of the condition is by use of the Boolean and operator (again for num equal to 15): 1<=num andnum<=10  (1<=num) and (num<=10)  True and (num<=10)  True and True  True Let’s see what we get when we do evaluate the expression in the Python shell (for num equal to 15) >>> 1<=num andnum<=10 False We actually get the correct result, False. If we were to try the original form of the expression: >>> 1<= num <=10 False This also works without error in Python?! Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 17. 17 What you need to be aware of is that Python allows a relational expression of the form, 1<= num <=10 but and automatically converts it to the form before evaluated, 1<=num andnum<=10 Thus, although Python offers this convenient shorthand, many programming languages require the longer form expression by use of logical and, and would give an error (or incorrect results) if written in the shorter form. Thus, as a novice programmer, it would be best not to get in the habit of using the shorter form expression particular to Python. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 18. Let’s Try It 18 What do each of the following relational expressions evaluate to? Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 19. Operator Precedence and Boolean Expressions George Boole, in the mid-1800s, developed what we now call Boolean algebra. His goal was to develop an algebra based on true/false rather than numerical values. Boolean algebra contains a set of Boolean (logical) operators, denoted by and, or, and not. These logical operators can be used to construct arbitrarily complex Boolean expressions. 19 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 20. 20 Operator Precedence and Boolean Expressions As we saw earlier, in the table, high-priority operators are placed before lower-priority operators. Thus we see that all arithmetic operators are performed before any relational or Boolean operators. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 21. 21 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions Unary Boolean operator not has higher precedence then and, and Boolean operator and has higher precedence than the or operator.
  • 22. 22 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions As with arithmetic expressions, it is good programming practice to use parentheses, even if not needed, to add clarity and enhance readability, If not all subexpressions,
  • 23. Let’s Try It 23 From the Python shell, enter the following and observe the results. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 24. Short-Circuit Evaluation There are differences in how Boolean expressions are evaluated in different programming languages. For logical and, if the first operand evaluates to false, then regardless of the value of the second operand, the expression is false. Similarly, for logical or, if the first operand evaluates to true, regardless of the value of the second operand, the expression is true. Because of this, some programming languages do not evaluate the second operand when the result is known by the first operand alone, called short-circuit (lazy) evaluation. 24 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 25. Subtle errors can result if the programmer is not aware of this. For example, the expression 25 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions would evaluate without error for all values of n when short-circuit evaluation is used. If programming in a language not using short-circuit evaluation, however, a “divide by zero” error would result when n is equal to 0. In such cases, the proper construction would be, In the Python programming language, short-circuit evaluation is used.
  • 26. Logically Equivalent Boolean Expressions In numerical algebra, there are arithmetically equivalent expressions of different form. For example, x(y + z) and xy + xz are equivalent for any numerical values x, y, and z. Similarly, there are logically equivalent Boolean expressions of different form. 26 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 27. Logically equivalent Boolean expressions of different form.
  • 28. Fundamental logically equivalent Boolean expressions. The last two equivalences are referred to as De Morgan’s Laws.
  • 29. Let’s Try It 29 From the Python shell, enter the following and observe the results. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 30. 30 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 31. 31 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 32. 32 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 33. 33 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 34. 34 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 35. 35 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 36. 36 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 37. 37 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 38. A selection control statement is a control statement providing selective execution of instructions. A selection control structure is a given set of instructions and the selection control statement(s) controlling their execution. Next, the if statement provides selection control in Python. 38 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control Selection Control
  • 39. If Statement An if statement is a selection control statement based on the value of a given Boolean expression. 39 Note that if statements may omit the “else” part. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 40. Below is a version of the temperature conversion program that allows the user to select a conversion of Fahrenheit to Celsius, or Celsius to Fahrenheit, implemented by the use of an if statement. 40 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 41. Indentation in Python One fairly unique aspect of Python is that the amount of indentation of each program line is significant. In most programming languages, indentation has no affect on program logic—it is simply used to align program lines to aid readability. In Python, however, indentation is used to associate and group statements. 41 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 42. A header in Python is a specific keyword followed by a colon. In the example, the if-else statement contains two headers, “if which 5 = 'F':” containing keyword if, and “else:” consisting only of the keyword else. Headers that are part of the same compound statement must be indented the same amount—otherwise, a syntax error will result. 42 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 43. The set of statements following a header in Python is called a suite (commonly called a block ). The statements of a given suite must all be indented the same amount. A header and its associated suite are together referred to as a clause. A compound statement in Python may consist of one or more clauses. While four spaces is commonly used for each level of indentation, any number of spaces may be used, as shown below. 43 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 44. Let’s Try It 44 From IDLE, create and run a Python program containing the code on the left and observe the results. Modify and run the code to match the version on the right and again observe the results. Make sure to indent the code exactly as shown. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 45. Multi-Way Selection Python provides two means of constructing multi-way selection—one involving multiple nested if statements, and the other involving a single if statement and the use of elif headers. 45 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 46. 46 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control Multi-Way Selection by Use of Nested If Statements
  • 47. Below is a version of the temperature conversion program that checks for invalid input, implemented by the use of nested if statements. 47 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 48. Let’s Try It 48 From IDLE, create and run a simple program containing the code below and observe the results. Make sure to indent the code exactly as shown. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 49. 49 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions Multi-Way Selection by Use of elif Header
  • 50. Let’s Try It 50 From IDLE, create and run a Python program containing the code below and observe the results. Make sure to indent the code exactly as shown. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 51. The following Python program (Figure 3-16) prompts the user for a given month (and year for February), and displays how many days are in the month. This program utilizes the following programming features: ➤ if statement ➤ elif header 51 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.1 Literals Number of Days in Month Program Let’s Apply It
  • 52. 52 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.1 Literals
  • 53. 53 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.1 Literals On line 7 , variable valid_input is initialized to True for input error- checking. Line 10 prompts the user for the month (1–12), stored in variable month. On line 15 the month of February is checked for. Line 24 checks if month is equal to 1, 3, 5, 7, 8, 10, or 12. If true, then num_days is assigned to 31. If not true, line 28 checks if month is equal to 4, 6, 9, or 11. If true, num_days is assigned to 30. If not true, then an invalid month value was entered, and valid_input is set to False. Finally, the number of days in the month is displayed only if the input is valid ( line 38 ).
  • 54. 54 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 55. 55 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 56. 56 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 57. 57 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 58. 58 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 59. 59 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 60. An iterative control statement is a control statement providing the repeated execution of a set of instructions. An iterative control structure is a set of instructions and the iterative control statement(s) controlling their execution. Because of their repeated execution, iterative control structures are commonly referred to as “loops.” We look at one specific iterative control statement next: the while statement. 60 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control Iterative Control
  • 61. While Statement A while statement is an iterative control statement that repeatedly executes a set of statements based on a provided Boolean expression (condition). All iterative control needed in a program can be achieved by use of the while statement. 61 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 62. As long as the condition of a while statement is true, the statements within the loop are (re)executed. Once the condition becomes false, the iteration terminates and control continues with the first statement after the while loop. Note that it is possible that the first time a loop is reached, the condition may be false, and therefore the loop would never be executed. 62 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 63. Execution steps for adding the first three integers by use of the previous while loop. 63 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 64. Input Error Checking The while statement is well suited for input error checking in a program. This is demonstrated in the revised version of the temperature conversion program. 64 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 65. The while loop is used to force the user to re-enter if neither an ‘F’ (for conversion to Fahrenheit) or a ‘C’ (for conversion to Celsius) is not entered. 65 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 66. Let’s Try It 66 In IDLE, create and run a simple program containing the code below and observe the results. Make sure to indent the code exactly as shown. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 67. Infinite Loops An infinite loop is an iterative control structure that never terminates (or eventually terminates with a system error). Infinite loops are generally the result of programming errors. For example, if the condition of a while loop can never be false, an infinite loop will result when executed. 67 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 68. Following is an example program containing an infinite loop. 68 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control The while loop is an infinite loop (for any value of n 1 or greater) because the value of current is not incremented.
  • 69. Let’s Try It 69 From IDLE, create and run a simple program containing the code below and observe the results. Indent the code exactly as shown. To terminate an executing loop, hit ctrl-C. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 70. Definite vs. Indefinite Loops A definite loop is a program loop in which the number of times the loop will iterate can be determined before the loop is executed. Following is an example of a definite loop. 70 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control Although it is not known what the value of n will be until the input statement is executed, its value is known by the time the while loop is reached. Thus, it will execute “n times.”
  • 71. An indefinite loop is a program loop in which the number of times that the loop will iterate cannot be determined before the loop is executed. 71 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control In this case, the number of times that the loop will be executed depends on how many times the user mistypes the input.
  • 72. Boolean Flags and Indefinite Loops Often the condition of a given while loop is denoted by a single Boolean variable, called a Boolean flag. 72 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 73. Boolean variable valid_entries on line 12 in the following program is an example of the use of a Boolean flag for controlling a while loop. 73 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.3 Selection Control
  • 74. The following program implements an exercise for children learning to count change. It displays a random value between 1 and 99 cents, and asks the user to enter a set of coins that sums exactly to the amount shown. The program utilizes the following programming features: ➤ while loop ➤ if statement ➤ Boolean flag ➤ random number generator 74 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.1 Literals Coin Change Exercise Program Let’s Apply It
  • 75. 75 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.1 Literals
  • 76. 76 Introduction to Computer Science Using Python – Dierbach Copyright 2013 JohnWiley and Sons Section 2.1 Literals On line 18, function randint (imported on line 3) is called to randomly generate a coin value for the user to match, stored in variable amount. On line 13 Boolean variable terminate is initialized to False, used to determine when the program terminates. The game begins on line 17. The while loop is re-executed for each new game played (while terminate is False). The while loop on line 23 is re-executed while the current game is still in play (while game_over is false). The game ends when either the user enters a blank line, in which case the result is displayed and game_over is set to True (lines 37–43), or if the total amount exceeds the amount to be matched On line 26, a third Boolean flag is used, valid_entry, for controlling whether the user should be prompted again because of invalid input (on lines 45–48 ). Note the use of membership operator in (line 32).
  • 77. 77 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 78. 78 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 79. 79 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 80. 80 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 81. 81 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 82. 82 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 83. 83 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 3.2 Boolean Expressions
  • 84. 84 We look at the problem of displaying a given calendar month. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program Calendar Month Program
  • 85. Calendar Month The Problem 85 The problem is to display a calendar month for any given month between January 1800 and December 2099. The format of the month should be as shown. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
  • 86. Calendar Month Problem Analysis 86 Two specific algorithms are needed for this problem. First, we need an algorithm for computing the first day of a given month for years 1800 through 2099. This algorithm is given in Chapter 1. The second needed algorithm is for appropriately displaying the calendar month, given the day of the week that the first day falls on, and the number of days in the month. We shall develop this algorithm. The data representation issues for this problem are straightforward. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
  • 87. Calendar Month Program Design 87 Meeting the Program Requirements We will develop and implement an algorithm that displays the month as given. There is no requirement of how the month and year are to be entered. We shall therefore request the user to enter the month and year as integer values, with appropriate input error checking. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
  • 88. Calendar Month Program Design 88 Data Description What needs to be represented is the month and year entered, whether the year is a leap year, the number of days in the month, and which day the first of the month falls on. Given that information, the calendar month can be displayed. The year and month will be entered and stored as integer values, represented by variables year and month, year = 2012 month = 5 The remaining values will be computed by the program based on the given year and month, as given below, leap_year num_days_in_month day_of_week Variable leap_year holds a Boolean (True/False) value. Variables num_days_ in_month and day_of_week each hold integer values. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
  • 89. 89 Algorithmic Approach Algorithm for computing the day of the week. Have an algorithm for this. Recall that the result of this algorithm is a value between 0-6 indicating the day of the week that a given date falls on. For this program, we need only determine the day of the week for the first of the month. All the following days follow, for the given number of days in the month. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
  • 90. 90 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program The Overall Steps of the Program
  • 91. Calendar Month Program Implementation 91 • Prompts user for month and year. Validates that value entered for month correct (1-12), and that year entered is in the range 1800-2099, inclusive. • Determines whether the year is a leap year. Also determines the number of days in the month. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program Stage 1—Input Validation / Determining Leap Years and Number of Days in Month
  • 92. 92 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
  • 93. 93 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program Stage 1 Testing We add test statements that displays the number of days in the month, and whether the year is a leap year or not. The test run below indicates that these values are correct for the given month and year.
  • 94. 94 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program A Set of Test Cases
  • 95. Program Implementation 95 Stage 2 of the program includes the code for determining the day of the week for the first day of a given month and year, with a final print statement displaying the test results. Note that for testing purposes, there is no need to convert the day number into the actual name (e.g., “Monday”)—this “raw output” is good enough. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program Stage 2—Determining the Day of the Week
  • 96. 96 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
  • 97. 97 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
  • 98. 98 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program Stage 2 Testing Following is the output of a test run of the program. The day of the week value displayed is 1 (Sunday) which is the correct day of the week for the date entered.
  • 99. 99 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program A Set of Test Cases for Stage 2 Testing
  • 100. Program Implementation 100 In the final stage of the program we add the code for displaying a calendar month. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program Final Stage – Displaying the Calendar Month
  • 101. 101 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
  • 102. 102 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
  • 103. 103 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
  • 104. 104 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
  • 105. 105 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
  • 106. 106 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program Stage 2 Testing Following is the output of a test run of the program. The month displayed is obviously incorrect, since each week is displayed with eight days! The testing of all other months produces the same results. Since the first two stages of the program were successfully tested, the problem must be in the code added in the final stage.
  • 107. 107 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program Lines 128–129 is where the column is reset back to column 1 and a new screen line is started, based on the current value of variable current_col,
  • 108. 108 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program Variable starting_col is set to the value (0-6) for the day of the week for the particular month being displayed. Variable current_col is initialized to 1 at line 108 , and is advanced to the proper starting column on lines 113–115 .
  • 109. 109 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program Since the day of the week results have been successfully tested, we can assume that current_col will have a value between 0 and 6. With that assumption, we can step though lines 125–129 and see if this is where the problem is.
  • 110. 110 Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program Lines 128–129 is where the column is reset back to column 1 and a new screen line is started, based on the current value of variable current_col, if current_col <= 7: current_col = current_col + 1 else: current_col + 1 print()
  • 111. Now it is clear what the problem is—the classic “off by one” error! The condition of the while loop should be current_col < 7, not current_col <= 7. Current_col should be reset to 1 once the seventh column has been displayed (when current_col is 7). Using the <= operator causes current_col to be reset to 1 only after an eighth column is displayed. Deskchecking the Program Segment We check what happens as the value of current_col approaches 7. Stepping through a program on paper is referred to as deskchecking. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program 111
  • 112. Although the column error has been corrected, we find that the first of the month appears under the wrong column! The month should start on a Wednesday (fourth column), not a Thursday column (fifth column). After re-executing the program with this correction we get the following output. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program 112
  • 113. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program 113 Other months are tested, each found to be off by one day. We therefore look at lines 113–115 that are responsible for moving over the cursor to the correct starting column, while current_col <= starting_col: print(blank_column, end = '') current_col = current_col + 1 We consider whether there is another “off by one” error. Reconsidering the condition of the while loop, we realize that, in fact, this is the error. If the correct starting column is 4 (Wednesday), then the cursor should move past three columns and place a 1 in the fourth column. The current condition, however, would move the cursor past four columns, thus placing a 1 in the fifth column (Thursday). The corrected code is while current_col < starting_col: print(' ', end = '') current_col = current_col + 1
  • 114. Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program 114 The month is now correctly displayed. We complete the testing by executing the program on a set of test cases.