Title arial bold 28pt
Dr. Adrian Euler
adrian. .uk
Lecture 2
Control Structures
SMM283
Introduction to Python
www.cass.city.ac.uk
1
2
Objectives
After completing this session, you will be able to:
Write a loop to repeat a sequence of actions a fixed number of times
Write a loop to traverse the sequence of characters in a string
Write a loop that counts down and a loop that counts up
Write an entry-controlled loop that halts when a condition becomes false
www.cass.city.ac.uk
2
3
Objectives
Use selection statements to make choices in a program
Construct appropriate conditions for condition-controlled loops and selection statements
Use logical operators to construct compound Boolean expressions
Use a selection statement and a break statement to exit a loop that is not entry-controlled
Implement various numerical and financial applications
www.cass.city.ac.uk
FROM REVIOUS SESSION…
www.cass.city.ac.uk
String Literals
In Python, a string literal is a sequence of characters enclosed in single or double quotation marks
” and “” represent the empty string
Use ”’ and “”” for multi-line paragraphs
www.cass.city.ac.uk
Escape Sequences
The newline character \n is called an escape sequence
FIGURE 1.0 Some escape sequences in Python
www.cass.city.ac.uk
Variables and the Assignment Statement
Programmers use all uppercase letters for symbolic constants
Examples: TAX_RATE and STANDARD_DEDUCTION
Variables receive initial values and can be reset to new values with an assignment statement
www.cass.city.ac.uk
Integer and floating-point numbers
In real life, the range of integers is infinite
A computer’s memory places a limit on magnitude of the largest positive and negative integers
Python’s int typical range: –231 to 231 – 1
Integer literals are written without commas
Floating-Point Numbers
Python uses floating-point numbers to represent real numbers
Python’s float typical range: –10308 to 10308 and
Typical precision: 16 digits
www.cass.city.ac.uk
8
Arithmetic Expressions
An arithmetic expression consists of operands and operators combined in a manner that is already familiar to you from learning algebra
FIGURE 1.1 Arithmetic operators
www.cass.city.ac.uk
9
Character Sets
In Python, character literals look just like string literals and are of the string type
They belong to several different character sets, among them the ASCII set and the Unicode set
ASCII character set maps to set of integers ord() and chr() convert characters to and from ASCII
www.cass.city.ac.uk
The math Module
To use a resource from a module, you write the name of a module as a qualifier, followed by a dot (.) and the name of the resource
Example: math.pi, math.sqrt(), math.pow()
www.cass.city.ac.uk
The math Module
You can avoid the use of the qualifier with each reference by importing the individual resources
You may import all of a module’s resources to use without the qualifier
Example: from math import *
www.cass.city.ac.uk
REPETETIVE STRUCTURES
THE FOR LOOP
www.cass.city.ac.uk
Definite Iteration: The for Loop
Repetition statements (or loops) repeat an action
Each repetition of action is known as pass or iteration
Two types of loops
Those that repeat action a predefined number of times (definite iteration)
Those that perform action until program determines it needs to stop (indefinite iteration)
www.cass.city.ac.uk
Executing a Statement a Given Number of Times
Python’s for loop is the control statement that most easily supports definite iteration
The form of this type of loop is:
loop header
statements in body must be indented and aligned in the same column
loop body
www.cass.city.ac.uk
Executing a Statement a Given Number of Times
Example: Loop to compute an exponentiation for a non-negative exponent
If the exponent were 0, the loop body would not execute and value of product would remain as 1
www.cass.city.ac.uk
16
Count-Controlled Loops
Loops that count through a range of numbers
To specify an explicit lower bound:
www.cass.city.ac.uk
Count-Controlled Loops
Example: bound-delimited summation
www.cass.city.ac.uk
Augmented Assignment
Augmented assignment operations:
Format:
Equivalent to:
www.cass.city.ac.uk
Loop Errors: Off-by-One Error
Example:
Loop actually counts from 1 through 3
This is not a syntax error, but rather a logic error
www.cass.city.ac.uk
Traversing the Contents of a Data Sequence
range returns a list
Strings are also sequences of characters
Values in a sequence can be visited with a for loop:
Example:
www.cass.city.ac.uk
Specifying the Steps in the Range
range expects a third argument that allows you specify a step value
Example in a loop:
www.cass.city.ac.uk
Loops That Count Down
Example:
www.cass.city.ac.uk
Step Values for the range Function
Example: Program requests
amount deposited
annual rate of interest
then calculates balance after each quarter-year for four quarters.
www.cass.city.ac.uk
Formatting Text for Output
Many data-processing applications require output that has tabular format
Field width: Total number of data characters and additional spaces for a datum in a formatted string
www.cass.city.ac.uk
Formatting Text for Output
This version contains format string, format operator %, and single data value to be formatted
To format integers, letter d is used instead of s
To format sequence of data values:
www.cass.city.ac.uk
Formatting Text for Output
To format data value of type float:
where .
Examples:
www.cass.city.ac.uk
A SIMPLE Investment Report
The user interface for the investment report program:
Design:
Receive the user’s inputs and initialize data
Display the table’s header
Compute results for each year and display them
Display the totals
www.cass.city.ac.uk
A SIMPLE Investment Report
Coding:
www.cass.city.ac.uk
CONDITIONAL STRUCTURES
THE IF, IF-ELSE, IF-ELIF-ELSE
www.cass.city.ac.uk
Selection: if and if-else Statements
Selection statements allow a computer to make choices
Based on a condition
www.cass.city.ac.uk
The Boolean Type, Comparisons, and Boolean Expressions
Boolean data type consists of two values: true and false (typically through standard True/False)
Example: 4 != 4 evaluates to False
FIGURE 1.2 Comparison Operators
www.cass.city.ac.uk
if-else Statements
Also called a two-way selection statement
Often used to check inputs for errors:
Syntax:
Example
www.cass.city.ac.uk
if-else Statements (continued)
The semantics of the if-else statement
Better alternative:
www.cass.city.ac.uk
One-Way Selection Statements
Simplest form of selection is the if statement
FIGURE 1.4 Semantics of the if-statement
www.cass.city.ac.uk
35
Multi-way if Statements (continued)
A program may be faced with testing conditions that entail more than two alternative courses of action
Syntax:
www.cass.city.ac.uk
Multi-way if Statements (continued)
Example:
www.cass.city.ac.uk
Logical Operators and Compound Boolean Expressions
Often a course of action must be taken if either of two conditions is true: Below are two approaches
Could we use the and logical operator instead?
www.cass.city.ac.uk
Logical Operators and Compound Boolean Expressions
Boolean tables
www.cass.city.ac.uk
Simplifying Conditions
Use of De Morgan’s Laws
not(cond1 and cond2)
is the same as
not(cond1) or not(cond2)
not(cond1 or cond2)
is the same as
not(cond1) and not(cond2)
www.cass.city.ac.uk
Logical Operators and Compound Boolean Expressions
Next example verifies some of the claims made in the previous truth tables:
The logical operators are evaluated after comparisons but before the assignment operator
not has higher precedence than and and or
www.cass.city.ac.uk
Logical Operators and Compound Boolean Expressions (continued)
FIGURE 1.3 Operator precedence order from highest to lowest
www.cass.city.ac.uk
Short-Circuit Evaluation
In (A and B), if A is false, then so is the expression, and there is no need to evaluate B
In (A or B), if A is true, then so is the expression, and there is no need to evaluate B
Short-circuit evaluation: Evaluation stops as soon as possible
www.cass.city.ac.uk
Nested if-else Statements
Example: Program requests costs, revenue for company
Displays “Break even”, profit, or loss
www.cass.city.ac.uk
Testing Selection Statements
Tips:
Make sure that all of the possible branches or alternatives in a selection statement are exercised
After testing all of the actions, examine all of the conditions
Test conditions that contain compound Boolean expressions using data that produce all of the possible combinations of values of the operands
www.cass.city.ac.uk
REPETETIVE STRUCTURES
THE WHILE LOOP
www.cass.city.ac.uk
Conditional Iteration: The while Loop
The while loop can be used to describe conditional iteration
Example: A program’s input loop that accepts values until user enters a sentinel that terminates the input
www.cass.city.ac.uk
The Structure and Behavior of a while Loop
Conditional iteration requires that condition be tested within loop to determine if it should continue
Called continuation condition
Improper use may lead to infinite loop
while loop is also called entry-control loop
Condition is tested at top of loop
Statements within loop can execute zero or more times
www.cass.city.ac.uk
The Structure and Behavior of a while Loop
FIGURE 1.8 Semantics of the while loop
www.cass.city.ac.uk
data is the loop control variable
The Structure and Behavior of a while Loop (continued)
www.cass.city.ac.uk
Count Control with a while Loop
www.cass.city.ac.uk
The while True Loop and the break Statement
while loop can be complicated to write correctly
Possible to simplify its structure and improve its readability
www.cass.city.ac.uk
The while True Loop and the break Statement (continued)
Alternative: Use a Boolean variable to control loop
www.cass.city.ac.uk
RANDOM VARIABLES
Programming languages include resources for generating random numbers
www.cass.city.ac.uk
Random Numbers
random module supports several ways to do this
randint returns random number from among numbers between two arguments, included
Print a random value between 0.0 to 1.0
www.cass.city.ac.uk
RANDOM NUMBERS
Generating real numbers in a range
www.cass.city.ac.uk
Random Numbers
Example: A simple guessing game
www.cass.city.ac.uk
Loop Logic, Errors, and Testing
Errors to rule out during testing while loop:
Incorrectly initialized loop control variable
Failure to update this variable correctly within loop
Failure to test it correctly in continuation condition
To halt loop that appears to hang during testing, type Control+c in terminal window or IDLE shell
If loop must run at least once, use a while True loop with delayed examination of termination condition
Ensure a break statement to be reached eventually
www.cass.city.ac.uk
READING THIS WEEK
Lecturer notes, which map to
SCHNEIDER, I. D., (2015), An Introduction to Programming Using Python, Global Edition
Chapter 3
LAMBERT, A. K., (2012), Fundamentals of Python: First Programs, 1st Edition
Chapter 3 & 4
DEITEL M., H., DEITEL & ASSOCIATES, (2002), Python How to Program
Chapter 2
Additional Resources
Python Tutorial:
http://docs.python.org/tut/
59
www.cass.city.ac.uk
HOMEWORK THIS WEEK
See separate file on Moodle.
60
www.cass.city.ac.uk