Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
2 views43 pages

Python Lecture 3 - While and For

Uploaded by

b12502059
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views43 pages

Python Lecture 3 - While and For

Uploaded by

b12502059
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Computer Programming

-- Python
Lecture 3
Repetition Structures
Dr. I-Fan Lin
Copyright © 2018 Pearson Education, Ltd.
Introduction to Repetition
Structures
• Often have to write code that performs the
same task multiple times
– Disadvantages to duplicating code
• Makes program large
• Time consuming
• May need to be corrected in many places
• Repetition structure: makes computer repeat
included code as necessary
– Includes condition-controlled loops and count-
controlled loops
2
The while Loop: a Condition-
Controlled Loop
• while loop: while condition is true, do
something
– Two parts:
• Condition tested for true or false value
• Statements repeated as long as condition is true
– In flow chart, line goes back to previous part
– General format:
while condition:
statements

3
The while Loop: a Condition-
Controlled Loop

This condition is tested

4
The while Loop: a Condition-
Controlled Loop
• 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
• while loop is known as a pretest 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

5
The while Loop: a Condition-
Controlled Loop

2024/8/27 6
Example
A project currently underway at Chemical Labs, Inc. requires that a substance be
continually heated in a vat. A technician must check the substance’s temperature
every 15 minutes. If the substance’s temperature does not exceed 102.5 degrees
Celsius, then the technician does nothing. However, if the temperature is greater
than 102.5 degrees Celcius, the technician must turn down the vat’s thermostat,
wait 5 minutes, and check the temperature again. The technician repeats these
steps until the temperature does not exceed 102.5 degrees Celcius.

1.Get the substance’s temperature


2.Repeat the following steps as long as the temperature is greater than 102.5
degrees Celcius:
a. Tell the technician to turn down the thermostat, wait 5 minutes, and check the temperature again
b. Get the substance’s temperature
3.After the loop finishes, tell the technician that the temperature is acceptable and
to check it again in 15 minutes.

7
Example Codes

8
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

9
Infinite Loops – Example

10
The for Loop:
a Count-Controlled Loop
• Count-Controlled loop: iterates a specific
number of times
– 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

11
The for Loop: a Count-
Controlled Loop

12
The for Loop: a Count-
Controlled Loop

13
Using the range Function
with the for Loop
• The range function simplifies the process
of writing a for loop
– range returns an iterable object
• Iterable: contains a sequence of values that can be
iterated over
• range characteristics:
– One argument: used as ending limit
– Two arguments: starting value and ending limit
– Three arguments: third argument is step value

14
Using the range Function
with the for Loop

15
Using the Target Variable
Inside the Loop
• Purpose of target variable is to reference
each item in a sequence as the loop iterates
• Target variable can be used in calculations
or tasks in the body of the loop
– Example: calculate square root of each number in a
range

16
Letting the User Control
the Loop Iterations
• Sometimes the programmer does not know
exactly how many times the loop will execute
• Can receive range inputs from the user,
place them in variables, and call the range
function in the for clause using these
variables
– Be sure to consider the end cases: range does
NOT include the ending limit

17
Letting the User Control
the Loop Iterations

18
Letting the User Control
the Loop Iterations

19
Generating an Iterable Sequence that
Ranges from Highest to Lowest
• The range function can be used to generate
a sequence with numbers in descending
order
– Make sure starting number is larger than end
limit, and step value is negative
– Example: range (10, 0, -1)
10, 9, 8, 7, 6, 5, 4, 3, 2, 1

20
Checkpoint
• What will the following code display?
for number in range(6):
print(number)

• What will the following code display?


for number in range(2, 6):
print(number)
• What will the following code display?
for number in range(0, 501, 100):
print(number)

• What will the following code display?


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

21
Calculating a Running Total
• Programs often need to calculate a total of a series of
numbers
– Typically include two elements:
• A loop that reads each number in series
• An accumulator variable
– Known as program that keeps a running total: accumulates total
and reads in series
– At end of loop, accumulator will reference the total

2024/8/27 22
Calculating a Running Total

23
The Augmented Assignment
Operators
• In many assignment statements, the variable on
the left side of the = operator also appears on
the right side of the = operator
• Augmented assignment operators: special set of
operators designed for this type of job
– Shorthand operators

24
Checkpoint
• What will the following code display?
total = 0
for count in range(1, 6):
total = total + count
print(total)

• What will the following code display?


number1 = 10
number2 = 5
number1 += number2
print(number1)
print(number2)

25
Sentinels

• Sentinel: special value that marks the end of


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

26
Sentinels Example
The county tax office calculates the annual taxes on property using the following
formula:
property tax = property value * 0.0065

Every day, a clerk in the tax office gets a list of properties and has to calculate the
tax for each property on the list. You have been asked to design a program that the
clerk can use to perform these calculations.
Each property is assigned a lot number, and all lot numbers are 1 or greater.
You decide to write a loop that uses the number 0 as a sentinel value. During each
loop iteration, the program will ask the clerk to enter either a property’s lot
number, or 0 to end.

27
Sentinels Example

28
Input Validation Loops

• Computer cannot tell the difference between


good data and bad data
– If user provides bad input, program will produce
bad output
– GIGO: garbage in, garbage out
– It is important to design program such that bad
input is never accepted

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

30
Input Validation Loops
Example
Samantha owns an import business, and she calculates the retail prices of her
products with the following formula:
retail price = wholesale cost * 2.5

31
Input Validation Loops
Example with Validation

32
Nested Loops

• Nested loop: loop that is contained inside


another loop
– Example: analog clock works like a nested loop
• Hours hand moves once for every twelve movements
of the minutes hand: for each iteration of the “hours,”
do twelve iterations of “minutes”
• Seconds hand moves 60 times for each movement of
the minutes hand: for each iteration of “minutes,” do
60 iterations of “seconds”

33
Nested Loops

• 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 of iterations of inner loop X number of iterations of outer loop

34
Nested Loops Examples

35
Nested Loops (Comparison)

36
Nested Loops Examples

37
Practice
• Compute the sum of all multiples of 3 and 5
that are less than 100

38
Practice (Answer Keys)
Method 1:

Method 2:

Method 3:
Method 4:

39
Break and Continue Statements
• break: immediately terminates a loop entirely
• Continue: immediately terminates the current loop
iteration
while expression:
statement
statement
break
statement
statement
continue
statement
statement

statement

40
Exercise I
• The distance a vehicle travels can be calculated as follows:
distance = speed * time
For example, if a train travels 40 miles per hour for three
hours, the distance traveled is 120 miles. Write a program that
asks the user for the speed of a vehicle (in miles per hour) and
the number of hours it has traveled. It should then use a loop
to display the distance the vehicle has traveled for each hour
of that time period. Here is an example of the desired output:

41
Exercise II
• In mathematics, the notation n! represents the factorial of
the nonnegative integer n. The factorial of n is the product
of all the nonnegative integers from 1 to n. For example,
7! = 1×2×3×4×5×6×7= 5040
and
4! = 1×2×3×4= 24
Write a program that lets the user enter a nonnegative integer
then uses a loop to calculate the factorial of that number.
Display the factorial

42
Exercise III
• Write a program that uses nested loops to draw this pattern:
##
##
# #
# #
# #
# #

43

You might also like