Chap 4

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

Chapter 4

Repetition structures

Topics
 Introduction to Repetition Structures
 The while Loop: a Condition-Controlled Loop
 The for Loop: a Count-Controlled Loop
 Calculating a Running Total
 Sentinels
 Input Validation Loops
 Nested Loops

1
Introduction to Repetition
Structures
 Often have to write code that performs the same task multiple times
 e.g.: Suppose that you need to print a string (e.g., "Programming is
fun!") 100 times. It would be tedious to have to write the following
statement 100 times:
print("Programming is fun!")
print("Programming is fun!")
: 100 statements
:
print("Programming is fun!")

Introduction to Repetition
Structures
 Disadvantages to duplicating code
1) The duplicated code makes the program large.
2) Writing a long sequence of statements can be time consuming.
3) If part of the duplicated code has to be corrected or changed
then the correction or changes may need to be corrected in many
places
print("Programming is fun!")
print("Programming is fun!")
:
:
print("Programming is fun!")

2
Introduction to Repetition
Structures
 Repetition structure: makes computer repeat included code as
necessary
 Types of loop :
1. condition-controlled loops
• Uses a true/false condition to control the number of times that
it repeats
2. count-controlled loops
• Repeats a specific number of times

Pre-Test Loop
 The condition is checked at the
false beginning of each iteration.
Condition
 If it is TRUE, the loop continues.
true Otherwise, the loop terminate.
Actions  This structure is possible not executing
any actions at all.

3
Pre-Test Loop
Example:
Counter = 1
WHILE Counter <= 100
Print “Mr. Loh loves me.”
Counter = Counter + 1
ENDWHILE
Print Counter

Loop Initialization and Update


• Other than condition, commonly there are 2 more processes
(initialization and updating) associate with loops.

Initialization

SET numStud = 1

Condition WHILE numStud <= 3


OUTPUT “Congratulation”
numStud = numStud + 1
ENDWHILE
Action
OUTPUT “You are late”
Updating

4
The while Loop:
 a Condition-Controlled Loop
• while a condition is true, do something
Two parts:
• Condition tested for true or false value
• Statements repeated as long as condition is true
In flowchart, line goes back to previous part

The while Loop: (cont’d.)


• General format:
while condition:
statements

5
Extra: while vs. if else

False True
condition

statements statements

The while Loop: (cont’d.)


 In order for a loop to stop executing, something has to happen
inside the loop to make the condition false
 Iteration: one execution of the body of a loop
–Tests condition before performing an iteration
◦ Will never execute if condition is false to start with
◦ Requires performing some steps prior to the loop to make sure
that the loop executes at least once.
◦ E.g.: count = 0

6
while Loop Example
count = 0
while count < 3:
print("Programming is fun!")
count = count + 1

Question: what is the count value when exit loop?

Start

Example Set cont to


“Y”

cont = “Y”
False cont True
while cont == “Y”:
= “Y”
print(“GG”)
cont=input(“print again (Y/N): ”)
Print
“GG”

End
Get
cont

7
Infinite Loops
Loops must contain within themselves a way to terminate
◦ Something inside a while loop must eventually make the condition
false
Infinite loop: loop that does not have a way of stopping
◦ Repeats until program is interrupted
◦ Occurs when programmer forgets to include stopping code in the loop
◦ The only way to stop this program is to press Ctrl+C on the keyboard to
interrupt it.

Exercise 1:
Show the errors in the following code:

a) b)
count = 0 count = 0
while count < 100: while count < 100:
print(count) print(count)
count -= 1

8
Exercise 2:
How many times will 'Hello World ' be printed in the following
program?
count = 10
while count < 1:
print('Hello World')

Exercise 3.1
Write a program with while loop that print out all the numbers from 1 to 10.
Example output:
1
2
3
4
5
6
7
8
9
10

9
Exercise 3.2
Modify the previous program to print all the numbers from 1 to 10 in reverse order.
Example output:
10
9
8
7
6
5
4
3
2
1

Exercise 3.3
Modify the previous program to print all the following numbers:
10
8
6
4
2

10
Exercise 4
Write a program that allows the user to enter 2 numbers then displays a
series of numbers from the 1st number to 2nd number.
Sample output 1:
Enter 1st number: 9
Enter 2nd number: 13
9
10
11
12
13

Calculating a Running Total


o Programs often need to calculate a total of a series of numbers
o Typically include two elements:
1. A loop that reads each number in series
2. An accumulator variable
o The variable that is used to accumulate the total of the numbers is
called an accumulator. It is often said that the loop keeps a running
total because it accumulates the total as it reads each number in the
series.
oAt end of loop, accumulator will reference the total

11
Calculating a Running Total (cont’d.)
total = 0
count = 1
while count <= 4:
print(count)
total = total + count
count += 1
print(total)

total =
total count count<=4 print(count) count += 1
total + count

Calculating 01a Running


1
2
1<=4
2<=4 Total
1
2 (cont’d.)
1
3
2
3
3 3 3<=4 3 6 4
total = 0 6 4 4<=4 4 10 5
10 5 5<=4
count = 1
while count <= 4:
print(count)
total = total + count
count += 1
print(total)

12
Exercise 5
Write a program by using while loop that sum up all the numbers
from 1 to 10 and display the result.
Sample output:
1
2

9
10
Total is 55

Exercise 6
A student took 4 tests. Write a program that reads the score of four tests
and determine the total. Given that the score is an integer in the range 0
to 100.
Sample output:
Enter score 1: 60
Enter score 2: 40
Enter score 3: 52
Enter score 4: 81
Total is 233

13
The for Loop
o A Count-Controlled loop: iterates a specific number of times
o Use a for statement to write count-controlled loop
◦ Designed to work with sequence of data items
–Iterates once for each item in the sequence
◦ General format:
for variable in [val1, val2, etc]:
statements
◦ Target variable: the variable which is the target of the assignment
at the beginning of each iteration

The for Loop (extra example)


if num in [1,2,3,4,5]:
print “Hello”
print(“bye”)

14
The for Loop
for num in [1,2,3,4,5]:
print(num)
print(“bye”)
Program Output:
1
2
3
4
5
bye

The for Loop


for name in ['Mario', 'Adele', 'Lee Joon Gi']:
print(name)
list
Program Output:
Mario
Adele
Lee Joon Gi

15
Using the range Function with the
for Loop
o The range function simplifies the process of writing a for loop
o range returns an iterable object
◦ Iterable: contains a sequence of values that can be iterated
over
o Syntax:
for var in range(start, stop, step) :
statement
o The numbers in the range function must be integers

Using the range Function with the


for Loop
o Example:
for num in range(0,5,1): num = 0
print(num) while num < 5:
print(num)
Output: num += 1
0
1
2
3
4

16
Using the range Function with the
for Loop
Range characteristic 1 Range Characteristic 2 Range Characteristic 3

for x in range (4): for x in range (1,4): for x in range (1,4,2):


print(x) print(x) print(x)

Output: Output: Output:


0 1 1
1 2 3
2 3
3

Using the range Function with the


for Loop
E.g.1:
for x in range(5):
print('Hello world!')

E.g.2:
for num in range(5, 9):
print(num)

E.g.3:
for num in range(2, 10, 3):
print(num)

17
Generating an Iterable Sequence that
Ranges from Highest to Lowest
o The range function can be used to generate a sequence with
numbers in descending order
o Make sure starting number is larger than end limit, and step
value is negative
o E.g.: Prints the number 5 down to 1
for num in range(5, 0, -1):
print(num)

Exercise
1) What will the following code display?
for number in range(6):
print(number)

2) What will the following code display?


for number in range(2, 6):
print(number)

18
Exercise
3) What will the following code display?
for number in range(0, 501, 100):
print(number)

4) What will the following code display?


for number in range(10, 6, -1):
print(number)

Exercise
1.0 Write a program by using for loop that print out # for 8 times.
Sample output:
#########

1.1 Modify the previous program that allows the user to determine
number # to be displayed
Sample output:
Enter a number: 12
#############

19
Exercise
2.0 Write a program by using for loop that sum up all the numbers
from 1 to 10 and display the result.
Sample output:
1 2 3 4 5 6 7 8 9 10
Total is 55

Sentinels
o Sentinel: special value that marks the end of a sequence of items
o When program reaches a sentinel, it knows that the end of the
sequence of items was reached, and the loop terminates
o Must be distinctive enough so as not to be mistaken for a regular
value in the sequence
o Example: when reading an input file, empty line can be used as a
sentinel

20
Mr. Loh is handsome!
The while Loop with Sentinel value
Continue to print (Y/N): Y
Mr. Loh is handsome!
Continue to print (Y/N): Y
cont = “Y”
Mr. Loh is handsome!
while cont == “Y”: Continue to print (Y/N): N
print(“Mr. Loh is handsome!”)
cont = input(“Continue to print (Y/N): ”)

The while Loop with Sentinel value


total = 0
value = eval(input(“Enter a number (0 to stop):”))
while value != 0:
total = total + value
value = eval(input(“Enter a number (0 to stop):”))
print(total)

21
Exercise 1
Write a program to display a series of numbers from 1 until the user enters N.
Sample output:
1
Continue printing (Y/N): Y
2
Continue printing (Y/N): Y
3
Continue printing (Y/N): Y
4
Continue printing (Y/N): N

Exercise 2
Write a program which asks the user to key in some numbers (0 to stop),
displays "ODD" or "EVEN" after each one.
Enter a number (0 to stop): 6
Even
Enter a number (0 to stop): 11
Odd
Enter a number (0 to stop): 8
Even
Enter a number (0 to stop): 0

22
Input Validation Loops
o Computer cannot tell the difference between good data and bad data
o If user provides bad input, program will produce bad output, e.g.:
payroll program
 a negative number entered for the hours worked;
 an invalid hourly pay rate.
o GIGO: garbage in, garbage out
o It is important to design program such that bad input is never
accepted

Input Validation Loops (cont’d.)


o Input validation: inspecting input before it is processed by the
program
o If input is invalid, prompt user to enter correct data
o Commonly accomplished using a while loop which repeats as long
as the input is bad
o If input is bad, display error message and receive another set of
data
o If input is good, continue to process the input

23
Input Validation Loops (cont’d.)

Input Validation Loops (cont’d.)


o Example 1: Get a test score (0-100).

score = int(input('Enter a test score: '))


while score < 0 or score > 100:
print('ERROR: The score cannot be negative')
print('or greater than 100.')
score = int(input('Enter the correct score: '))

24
Extra Example:
Check for valid grade (A, B, C, D, F):

grade = input(“Enter a grade: ”)


while grade not in [“A”, “B”, “C”, “D”, “F”]:
print(“HELLO! Enter A,B,C,D or F only la”)
grade = input(“Enter a grade: ”)

Exercise
Write a python program to display a message according to the
following table. The program should display error message for
invalid level entered and allow the user to re-enter.

Level Message Enter an education level: x


F Foundation Enter an education level: t
Enter an education level: y
D Degree
Enter an education level: F
M Master Foundation

25
Nested Loops
o Nested loop: loop that is contained inside another loop
o Key points about nested loops:
Inner loop goes through all of its iterations for each iteration of outer
loop
Inner loops complete their iterations faster than outer loops
Total number of iterations in nested loop:
number_iterations_inner x number_iterations_outer

Using Nested Loops to Print Patterns


oTo print : oTo print :
****** ******
for col in range(6): ******
print('*', end='') ******
for row in range(3):
for col in range(6):
print('*', end='')
print()

26
Exercise
Write a program with the used of nested for loop to display the
following patterns
12345 54321 11111
12345 54321 22222
12345 54321 33333
12345 54321 44444

Using Nested Loops Enter mark: 60


Enter mark: 20
o to calculate total marks for 1 student Enter mark: 50
total = 0 Total is 130
for subj in range (3):
mark = eval(input(“Enter mark: ”))
total = total + mark
print(“Total is ”, total)

27
Using Nested Loops
o to calculate total marks for multiple students.
cont = “y”
while cont == “y”:
total = 0
for subj in range (3):
mark = eval(input(“Enter mark: ”))
total = total + mark
print(“Total is ”, total)
cont = input(“Anymore students (y/n)? ”)

The break Statement


o Causes an exit from anywhere in the body of a loop
o When break is executed
 Loop immediately terminates
o Break statements usually occur in if statements

28
TestBreak.py
1. sum = 0
2. number = 0
The break statement
3. while number < 5:
terminates the loop and
4. number += 1 executes the following
5. sum += number statements.
6. if sum >= 7:
7. break
8. print("The number is", number)
9. print("The sum is", sum);

Creating a Menu

29
The continue Statement
o When continue executed in a while loop
Current iteration of the loop terminates
Execution returns to the loop’s header
o Usually appear inside if statements.

TestContinue.py
1. sum = 0
2. number = 0
3. while number < 5: The continue statement
4. number += 1 skips the remaining
statements in the body of
5. if number == 3:
the loop and proceed with
6. continue the next iteration.
7. sum += number
8. print("The sum is", sum)

30
Summary
This chapter covered:
◦ Repetition structures, including:
Condition-controlled loops
Count-controlled loops
Nested loops
◦ Infinite loops and how they can be avoided
◦ range function as used in for loops
◦ Calculating a running total and augmented assignment operators
◦ Use of sentinels to terminate loops
◦ break statement
◦ continue statement

31

You might also like