COMP121L_Repetition_Structure
Lesson Overview
Lesson Title: Repetition Structure
Instructor: HANNAH SHAMIRA P. SANTONIL
Institution: Manuel S. Enverga University Foundation, College of Engineering
Learning Outcomes
Introduction to Repetition Structures
The while Loop: A Condition-Controlled Loop
The for Loop: A Count-Controlled Loop
Sentinels
Input Validation Loops
Nested Loops
Introduction to Repetition Structures
Definition: A repetition structure executes a statement or set of statements repeatedly.
Purpose: To avoid writing the same code multiple times, making code cleaner and more efficient.
Common term: Repetition structure is often referred to as a loop.
Types of Loops
Condition-Controlled Loops
Definition: Uses a true/false condition to control repetitions.
Implementation in Python: Usually written using the
while
statement.
Count-Controlled Loops
Definition: Repeats a specific number of times.
Implementation in Python: Written using the
for
statement.
The while Loop
Concept
Condition-Controlled: Executes a statement or block of statements as long as a specified condition is true.
Parts of the While Loop
Condition: Evaluated for true/false value.
Statements: Executed repeatedly while the condition is true.
General Format in Python
while condition:
statement
statement
Example 1: Calculating Sales Commissions
keep_going = 'y'
while keep_going == 'y':
sales = float(input('Enter the amount of sales: '))
comm_rate = float(input('Enter the commission rate: '))
commission = sales * comm_rate
print('The commission is $', format(commission, ',.2f'), sep='')
keep_going = input('Do you want to calculate another commission (Enter y for yes): ')
Program Output: Calculates the commission based on user input.
Figure 4-2: Logic Flow of the While Loop
If the condition is true, execute statements; if false, skip to exit.
Pretest Loop
The while loop is classified as a pretest loop, as it checks the condition before executing the loop.
Often requires initial steps to ensure execution at least once.
Example 2: Substance Heating Process
Algorithm
Get the substance's temperature.
Repeat the following steps while the temperature exceeds 102.5°C:
Adjust the thermostat and wait 5 minutes.
Check the temperature again.
After completion, advise technician to check temperature again in 15 minutes.
Example of Python code
MAX_TEMP = 102.5
temperature = float(input("Enter the substance's Celsius temperature: "))
while temperature > MAX_TEMP:
print('Temperature too high. Adjust thermostat and wait 5 minutes.')
temperature = float(input('Enter new temperature: '))
print('Temperature acceptable. Check in 15 minutes.')
The for Loop
Concept
Count-Controlled Loop: Iterates a specific number of times.
Syntax:
for variable in [value1, value2]:
statement
Using the Range Function
Purpose: Simplifies creating count-controlled loops by generating a sequence of numbers.
Basic Usage:
for num in range(5):
print(num)
Details: Generates numbers from 0 to 4.
Example: Using Range Function
With a single argument: Displays "Hello world" five times.
With two arguments: Defines start and end of the range:
for num in range(1, 5):
print(num)
With three arguments: Defines a start, end, and step:
for num in range(1, 10, 2):
print(num)
Using the Target Variable Inside the Loop
Definition: The target variable represents each item in the sequence as the loop iterates.
Example Task: Display numbers and their squares in a formatted table.
Nested Loops
Concept
Definition: A loop inside another loop.
Analogy: A clock with hands rotating at different rates.
Example: Digital Clock Simulation
Displays seconds from 0-59, nests minute count into that.
Sample Code: Nested Loop Program
num_students = int(input('How many students? '))
for student in range(num_students):
num_test_scores = int(input('How many test scores? '))
for test_num in range(num_test_scores):
score = float(input(': '))
total += score
average = total / num_test_scores
print('Average for student', student+1, 'is:', average)
Conclusion
Understanding repetition structures is crucial in programming for efficiency and functionality.