While Loop
While Loop
REVIEW: BRANCHING
PROGRAMS
Test
True False
Block Block
Code
GRADE
Score >=85 ==> A
Score >=70 but <85 ==> B
Score >=50 but <70 ==> C
Score >=40 but <50 ==> D
Score < 40 ==> F
DEFENSIVE PROGRAMMING
Defensive programming is a form
of defensive design intended to ensure
the continuing function of a piece of
software under unforeseen
circumstances.
INPUT
def add(a,b):
print(a+b)
assert
def add(a,b):
# check if a is int/float
# check if b is int/float
print(a+b)
UPDATING VARIABLES
>>> x = 5
# increment by one
>>> x = x + 1 >>> x += 1
# decrement by one
>>> x = x - 1 >>> x += 1
CASE STUDY: AVERAGE OF
THREE NUMBERS
▪ Average of 5
▪ Average of 20
▪ Average of 1000
▪ Two types
▪ while loop
▪ for loop
THE while LOOP
The while Loop is a Pretest Loop, which
means it tests its condition before
performing an iteration.
THE while LOOP
while(condition):
<statements>
THE while LOOP
More formally, here is the flow of execution for a
while statement:
I. Evaluate the condition, yielding True or
False.
II. If the condition is false, exit the while
statement and continue execution at the next
statement.
III. If the condition is true, execute the body
EXAMPLE 1
while(True):
print(‘hi’)
INFINITE LOOPS
x=1
while(x > 0):
x += 1
COMMON
PITFALLS
UNINTENTIONAL INFINITE
LOOP
x = 10
while(x > 0):
x += 1
OFF-BY-ONE ERROR(OB1)
A logic error that occurs in
programming when an iterative
loop iterates one time too many or
too few.
OB1
Arises when programmer makes
mistakes such as
▪ Fails to take account that a sequence
starts at zero rather than one
▪ Using “less than or equal to” in place of
“less than” …