Professional Documents
Culture Documents
Chap 4
Chap 4
Chap 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
Initialization
SET numStud = 1
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
5
Extra: while vs. if else
False True
condition
statements statements
6
while Loop Example
count = 0
while count < 3:
print("Programming is fun!")
count = count + 1
Start
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
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
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
14
The for Loop
for num in [1,2,3,4,5]:
print(num)
print(“bye”)
Program Output:
1
2
3
4
5
bye
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
16
Using the range Function with the
for Loop
Range characteristic 1 Range Characteristic 2 Range Characteristic 3
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)
18
Exercise
3) What will the following code display?
for number in range(0, 501, 100):
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): ”)
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
23
Input Validation Loops (cont’d.)
24
Extra Example:
Check for valid grade (A, B, C, D, F):
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.
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
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
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)? ”)
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