Chapter 3: Control Statements

Chapter 3: Control Statements

Selection statements allow a computer to make choices based on a condition

Boolean data type: True & False

Comparison operatorMeaning
==Equals
!=Not equals
<Less than
>Greater than
<=Less than or equal
>=Greater than or equal
  • Evaluated after arithmetic operators

One-way selection statement (if statement)

if x < 0:
x = -x
NOTE:
if x > 18: …
if x > 16: …
For e.g. x = 10, BOTH statements are printed (both if statements are run)

Two-way selection statement (if-else statement)

Syntax:
if <condition>:
<sequence of statements-1>
else:
<sequence of statements-2>
If-else statement can be used to check input for errors:
import math
area = float(input(“Enter the area:  ”))
if area > 0:
radius = math.sqrt(area / math.pi)
print(“The radius is”, radius)
else:
print(“Error: the area must be a positive number”)

Multi-way if statements

Testing conditions that entail >2 alternative courses of action
Syntax:
if <condition-1>:
<sequence of statements-1>
elif <condition-n>:
<sequence of statements-n>
else:
<default sequence of statements>

Multi-way if statements

E.g.
number = int(input(“Enter the numeric grade: ”))
if number > 89:
letter = ‘A’
elif number > 79:
letter = ‘B’
elif number > 69:
letter = ‘C’
else:
letter = ‘F’
print(“The letter grade is”, letter)
OR pseudocode using CASE statements:
Note: case clauses are tested in sequence
When a case that applies if found, its statement is executed and CASE statement is complete. Any remaining cases are not tested.
BEGIN
INPUT number
CASE OF number
> 89: letter ← ‘A’
> 79: letter ← ‘B’
> 69: letter ← ‘C’
OTHERWISE: letter ← ‘F’
ENDCASE
OUTPUT “The letter grade is”, letter
END

Logical Operators and Compound Boolean Expressions

  • To simplify code when there are multiple conditions to check
  • Logical operators: and, or, not
  • Evaluated after comparisons (==, !=, etc) but before assignment (=) operator
  • not has higher precedence than and and or (i.e. not is evaluated first)
ABA and BA or B
TrueTrueTrueTrue
TrueFalseFalseTrue
FalseTrueFalseTrue
FalseFalseFalseFalse
Anot A
TrueFalse
FalseTrue

Some nested if statements can be described as else-if statements

Nested if statements

score = int(input(“Enter score: ”))
print(“Grade of student is:”, end = “ ”)
if score>=90:
print(“A”)
else:
if score>=80:
print(“B”)
else:
if(score>=70):
print(“C”)
else:
print(“F”)

elif statements

score = int(input(“Enter score: ”))
print(“Grade of student is:”, end = “ ”)
// note: end = “ ” is so that wont print grade as a new line after “Grade of student is:”
if score>=90:
print(“A”)
elif score>=80:
print(“B”)
elif score>=80:
print(“C”)
else:
print(“F”)

Definite iteration: the for loop

  • Repetition statements (i.e. loops) repeat an action
  • Each repetition of action is known as pass or iteration
  • Iterative solution = a loop which converges to a solution
  • Successive values of its local variables are overwritten


Range function: generates a list of integers to help iterate loop; expects up to 3 arguments

  • Range (<upper bound + 1>)
>>> list(range(4))        # 1 argument
[0, 1, 2, 3]
  • With 1 argument only, the list starts from 0 and includes all numbers smaller than the argument
  • Range (<lower bound>, <upper bound + 1>)
>>> list(range(1,5))        # 2 arguments
[1, 2, 3, 4]
  • With 2 arguments, the list starts from the first argument and includes all numbers smaller than the second argument
  • Range (<lower bound>, <upper bound + 1>, step)
>>> list(range(1,6,1))        # Same as using 2 arguments
[1, 2, 3, 4, 5]
>>> list(range(1,6,2))        # Use every other number
[1, 3, 5]
>>> list(range(1,6,3))        # Use every 3rd number (3 is stride?)
[1, 4]
  • 3 arguments with a specified step value
  • When the 3rd parameter is negative, it becomes a list that counts down
>>> list(range(10,0,-1))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Loop

  • Execute a statement a given no. of times
  • A control statement that most easily supports definite iteration
for <variable> in range <an integer expression>):        # loop header
<statement-1>         # loop body (indent and align in same column)
<statement-n>
>>> number = 2
>>> exponent = 3
>>> product = 1
>>> for eachPass in range(exponent):
product = product * number
print(product, end = “   ”)
2 4 8
>>> product
8
# if exponent were 0, loop body would not execute and value of product would remain as 1

Control variable

  • Incrementing control variable by step of 1
FOR i ← 1 TO 4
OUTPUT i, “ squared is ”, i * i
ENDFOR
OUTPUT:
1 squared is 1 ← printed when i=1
2 squared is 4 ← printed when i=2
3 squared is 9 ← printed when i=3
4 squared is 16 ← printed when i=4
  • Decrementing control variable by step of 1
FOR i ← 4 TO 1 STEP -1
OUTPUT i, “ squared is ”, i * i
ENDFOR
OUTPUT:
4 squared is 16 ← printed when i=4
2 squared is 4 ← printed when i=2
3 squared is 9 ← printed when i=3
1 squared is 1 ← printed when i=1
  • Do not alter the control variable
  • A statement in the for loop body should never assign a value to the control variable
FOR i ← 1 TO 10
OUTPUT i
i ← i+2 // don’t do this
END FOR

Indentation

  • Clear indentation and indication of loop body
  • Block of statements (as loop body) must be contained within the ENDFOR markers
  • If not in loop, write after ENDFOR (i.e. after the loop), not indented but aligned with FOR and ENDFOR statement

Traversing the contents of a data sequence

  • Strings are also sequences of characters and values in a sequence can be visited with a for loop
  • for <variable> in <sequence>:
    <do something with variable>
>>> for character in “Hi there!”:
print(character, end = “ ”)
OUTPUT:
H i   t h e r e!

Processing input groups of data: general form in Top Down Design

Before:

Initialise any variables that need initialising
Print any headings

During:

FOR i ← ___ TO ___
output-input combination(s) to get info on 1 person or item
process that person’s or item’s info
ENDFOR

After:

Print any final tallies or results
# program counting to find no. of students (out of 5) who scored at least 90
BEGIN
count ← 0
FOR student ← 1 TO 5
# read in students’ score from user
OUTPUT “enter score of student ”, student, “: ”
INPUT score
IF score >= 90
count ← count + 1
ENDIF
ENDFOR
OUTPUT count, “ student(s) score at least 90”
END
count = 0
for student in range(1, 5+1):
print(“enter score of student ”, student, “:”, end = “ ”)
score = int(input())
if score >= 90:
count = count + 1
print(count, “ student(s) score at least 90”)

Initialising

  • A variable that is given a starting value before a loop is initialised
  • E.g. count = 0 initialises count to 0. In the subsequent loop, whenever there is a score at least 90, count is increased by 1
  • If count not initialised, starting value would be unreliable, might be a value left over from the previous run program
  • Even in pseudocode, should be clear that readers need not make own assumptions of initial value

During:

initialise maxSoFar with first number

FOR i ← 2 TO 5
read a number
test whether it is larger than maxSoFar
and if so change the value of maxSoFar
ENDFOR

After:

initialise maxSoFar with first number

print value of maxSoFar

Before:

# program maxOf5 to find maximum of 5 input positive integers
BEGIN
OUTPUT “enter first number: ”
INPUT maxSoFar
FOR i ← 2 TO 5
OUTPUT “enter text number: ”
INPUT numb
IF numb > maxSoFar
maxSoFar ← numb
ENDIF
ENDFOR
OUTPUT “the maximum is: ”, maxSoFar
END

Before:

maxSoFar = int(input(“enter first number: ”))
for i in range(2, 5+1):
numb = int(input(“enter next number: ”))
if numb >= maxSoFar:
maxSoFar =  numb
print(“the maximum is: ”, maxSoFar)

Variable limits

  • Can increase flexibility of a program by using variable(s) (e.g. n) as the upper or lower limit in the for header ⇒ no need to change any lines in the program to run for different number of groups of data
# program to find each employee’s wage and total payroll
BEGIN
# initialise total payroll
sum ← 0
OUTPUT “enter number of employees: ”
INPUT n
FOR employee ← 1 TO n
# get one employee’s data
OUTPUT “enter hours and rate of employee ”, employee
INPUT hours, rate
# process that data and print wage for one employee
wage ← hours * rate
sum ← sum + wage
OUTPUT “Wage of employee ”, employee, “is \$”, wage
ENDFOR
# print final result
OUTPUT “total payroll \$”, sum
END
sum = 0
n = int(input(“enter number of employees:”))
for employee in range(1, n+1):
print(“\nEnter hours and rate for employee ”, employee)
hours = float(input(“Hours: ”))
rate = float(input(“Rate: ”))
wage = hours * rate
sum = sum + wage
print(f“Wage of employee {employee} is ${wage:.2f}”) # rounding
print(f“total payroll ${sum:.2f}”)

Nested for Loops

  • The entire outer loop body is executed for each of the values of the outer loop control variable. Thus, for each value of the outer loop control variable, the inner for loop will through all of its values
FOR n ← 2 TO 3
FOR i ← 6 TO 7
OUTPUT n, “ ”, i
OUTPUT “hello”
ENDFOR
ENDFOR
OUTPUT:
# printed when n = 2
2 6
hello
2 7
hello
# printed when n = 3
3 6
hello
3 7
hello
num = 1
for i in range(2):
for i in range(3):
print(num)
num = num+1
print(num)
OUTPUT
1 2 3 4 5 6 7
WORKING:
For first outer loop:
1+1=2
2+1=3
3+1=4
For second outer loop:
4+1=5
5+1=6
6+1=7 # prints once out of loop

Conditional iteration: the while loop (aka entry-control loop)

  • Requires continuation condition tested within loop to determine if it should continue
  • Statements within loop can execute 0 or more times
  • while <condition>:
    <sequence of statements>
  • Pseudocode:
WHILE (test condition)
    # body of loop
ENDWHILE
  • Starts by testing the while condition
  • If condition is true, entire loop body is executed
  • Control is returned to the top to retest the while condition
  • Process repeated as long as while condition is true
  • [CAUTION!] improper use may lead to infinite loop
  • Post-control loop REPEAT UNTIL also behave like a while loop
  • Statements in the loop are executed at least once
  • Compared to while loop: will not run if condition is false
  • Condition is tested after statements are executed and if it evaluates to TRUE the loop termines, otherwise statements are executed again
n ← 7
WHILE(n>=0)
OUTPUT n
n ← n-5
OUTPUT ‘Hi ’, n
ENDWHILE
n ← 7
REPEAT
OUTPUT n
n ← n-5
OUTPUT ‘Hi ’, n
UNTIL n<0
OUTPUT:
# printed during 1st execution of loop body
7
Hi 2
# printed during 2nd execution of loop body
2
Hi -3

Loop logic, errors, and testing

  • Errors to rule out during testing while loop
  • Incorrectly initialised 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 Ctrl+C in terminal window or IDLE shell
  • Count controlled / fixed step-controlled while loops are similar to for loops: there is a control variable that inc./dec. by a fixed step
  • However, when it is a fixed number of iterations, for loop is always preferred (MUST use for instead of while for a levels if fixed no. of iterations)

Sum of all integers from 1 to 100000

Codes using for loop

sum = 0
for count in range(1, 100001):
sum += count
print(sum)

Codes using while loop

sum = 0
count = 1
while count <= 100000:
sum += count
count += 1
print(sum)

Countdown from 10 to 1

Codes using for loop

for count in range(10, 0, -1):
print(count, end=“ ”)

Codes using while loop

count = 10
while count >= 1:
print(count, end=“ ”)
count -= 1

All odd integers from 1 to 10

Codes using for loop

for i in range(1, 10[^c10][^c11], 2)
print(i)

Codes using while loop

i = 1
while i <= 9:
print(i)
i += 2
  • Data sentinel-controlled while loops
  • User can terminate data entry when he chooses by entering an appropriate signal known as sentinel
  • Type A: using a y or n question
# to find sum any no. of input integers (e.g. 15+47+53+64)
# user notifies computer that there is no further data by entering an n in response to the prompt type y to continue, n to stop
BEGIN
sum ← 0
ans ← ‘y’
WHILE ans = ‘y’
OUTPUT “enter number”
INPUT numb
sum ← sum + numb
OUTPUT “type y to continue, n to stop: ”
INPUT ans
ENDWHILE
OUTPUT “The sum is ”, sum
END
sum = 0
ans = “y”
while (ans == “y”) or (ans == “Y”):
numb = int(input(“enter number”))
sum = sum + numb
ans = input(“type y to continue, n to stop:”)
print(“The sum is”, sum)
  • Type B: Using a phony value -1
  • User signals an end to data entry by typing the phony value -1
BEGIN
sum ← 0
OUTPUT “enter number or -1 to stop: ”
INPUT numb
WHILE numb <> -1      # <> meaning less than or greater than (i.e. not equal to -1)
sum ← sum + numb
OUTPUT “enter number or -1 to stop: ”
INPUT numb
ENDWHILE
OUTPUT “The sum is ”, sum
END
# NOTE the 2 occurrences of the same output-input combination, once before the loop and once at the bottom of the loop body
  • Task-controlled while loop
  • When the condition for completion of the task is not a counter or a data sentinel
  • WHILE task not completed
    # loop body;
    ENDWHILE
# program to find first integer whose square puts the sum of squares over 1000
BEGIN
sum ← 0
n ← 0
WHILE sum <= 1000
n ← n+1
sum ← sum+n*n
ENDWHILE
OUTPUT “Sum first goes over 1000 when you add ”, n, “ squared”
OUTPUT “Sum is ”, sum
END
  • Multiple task-controlled WHILE loops
  • Use a compound condition in the exit test when there are 2 possible reasons for terminating a loop
  • Include an if-else test after the loop to determine which condition caused the exit
# User given max 3 tries to give the Capital of Indonesia. If user fails to give correct answer by 3rd try, he is informed what the correct answer is
BEGIN
STATE ← “Indonesia”
CAPITAL ← “Jakarta”
tries ← 1
OUTPUT “Give capital of”, STATE, “: ”
INPUT guess
WHILE(guess <> CAPITAL) AND (tries < 3)
OUTPUT “Give capital of”, STATE, “: ”
INPUT guess
tries ← tries + 1
ENDWHILE
IF guess = CAPITAL
OUTPUT “Nice work. You got it on try ”, tries
ELSE
OUTPUT “You did not get it in 3 tries”
OUTPUT “The correct answer is ”, CAPITAL
ENDIF
END

Error trapping and robustness

  • Robust programs contain safeguards like:
  • Include clear prompts so user knows the precise form of inputs
  • Include program code to detect and trap mistakes
# Program to determine if an input capital letter is in the 1st half (A-M) or 2nd half (N-Z) of the alphabet
BEGIN
OUTPUT “enter capital letter ”
INPUT letter
WHILE (letter < ’A’) OR (letter > ’Z’)
OUTPUT “*** Not a Capital Letter ***”
OUTPUT “enter capital letter ”
INPUT letter
ENDWHILE
IF (letter >= ’A’) AND (letter <= ’M’) # evaluated using ASCII value of the letter
OUTPUT letter, “ in 1st half of alphabet”
ELSE
OUTPUT letter, “ in 2nd half of alphabet”
ENDIF
END

Nested while loops

# Program to compute separate point totals for male and females. User will keep inputting data pairs such as 24 m and 47 f, where the first item of the data pair is the point total and the second is the sex of the player who achieved it
BEGIN
maleSum ← 0
femSum ← 0
ans ← ‘y’
WHILE (ans = ‘y’) OR (ans = ‘Y’)
OUTPUT “enter number of points”
INPUT points
OUTPUT “enter sex (m or f):”
INPUT sex
WHILE (sex <> ‘m’ AND (sex <> ‘f’)     # Error Trapping
OUTPUT “enter sex (m or f):”
INPUT sex
ENDWHILE
IF (sex = ‘m’)
maleSum ← maleSum + points
ELSE
femSum ← femSum + points
ENDIF
OUTPUT “Type y to continue, n to stop: ”
INPUT ans
ENDWHILE
OUTPUT “Total points for the male team: ”, maleSum
OUTPUT “Total points for the female team: ”, femSum
END

Comments from the Word document

Comments from the Word document