Weekly Programming Topics
Selection and Iteration
Week 5 - Selection and Iteration · Whatisin thislesson?
Selection and Iteration
Week 5 – Selection and Iteration
Whatisin thislesson?
- The Decision Structure
- The Relational Operators
- The if Statement
- The if-else Statement
- Logical Operators
- The Match Case in Python version 3.0
- Introduction to Repetition Structures
- The while Loop
- The for Loop:
- Processing List with Menu 11th January 2026 Tram Tran
Decision Structures and Boolean Logic
4-4
- The Decision Structure A control structure is a logical design that controls the order in which a set of statements execute.
- A sequence structure is a set of statements that execute in the order that they appear.
- A decision (or selection) structure is a control structure that can execute a set of statements and perform a specific action only if a certain condition exists. sequence decision
4-5
The Decision Structure Decision (selection) structure: Diamond symbol represents a true/false condition Single alternative decision structure provides only one alternative path of execution.
- 4-6
- The Relational Operators
- A relational operator determines whether a
- specific relationship exists between two values.
- Table 4-1 Relational operators
4-6
The Relational Operators A relational operator determines whether a specific relationship exists between two values. Table 4-1 Relational operators
4-7
The Relational Operators Boolean Expressions and Relational Operators Table 4-2 Boolean expressions using relational operators
4-8
The if Statement Concept: The if statement is used to create a decision structure, which allows a program to have more than one path of execution. The if statement causes one or more statements to execute only when a Boolean expression is true.
4-9
The if Statement Decision (selection) structure: In Python … if condition: statement statement statement etc.
4-10
The if-else Statement Concept: An if-else statement will execute one block of statements if its condition is true, or another block if its condition is false.
4-11
The if-else Statement A dual alternative decision structure provides two possible paths of execution – one path is taken if a condition is true, and the other path is taken if the condition is false.
- 4-12
- The if-else Statement
- Dual alternative
- In Python …
- if condition
4-12
The if-else Statement Dual alternative In Python … if condition: statement statement etc. else: statement statement etc.
4-13
Nested Decision Structures and the if-elif-else Statement Concept: To test more than one condition, a decision structure can be nested inside another decision structure.
4-14
Nested Decision Structures and the if-elif-else Statement
- 4-15
- Nested Decision Structures and the
- if-elif-else Statement
- The if-elif-else
- Statement
4-15
Nested Decision Structures and the if-elif-else Statement The if-elif-else Statement if condition_1: statement statement etc. elif condition_2: statement statement etc. else: statement statement etc. if score < 60: print ‘Your grade is F.’ elif score < 70: print ‘Your grade is D.’ elif score < 80: print ‘Your grade is C.’ elif score < 90: print ‘Your grade is B.’ else: print ‘Your grade is A.’
4-16
Logical Operators Concept: The logical and operator and the logical or operator allow you to connect multiple Boolean expressions to create a compound expression. The logical not operator reverses the truth of a Boolean expression.
4-17
Logical Operators Table 4-3 Logical operators
4-18
Logical Operators Table 4-4 Compound Boolean expressions using logical operators
4-19
Logical Operators The and Operator if temperature < 20 and minutes > 12: print ‘The temperature is in the danger zone.’ Table 4-5 Truth table for the and operator
4-20
Logical Operators The or Operator if temperature < 20 or temperature > 100: print ‘The temperature is too extreme.’ Table 4-6 Truth table for the or operator
4-21
Logical Operators The not Operator if not(temperature > 100): print ‘This is below the maximum temperature.’ Table 4-7 Truth table for the not operator
4-22
Logical Operators Checking Numeric Ranges with Logical Operators
if x >= 20 and x <= 40:
print ‘The value is in the acceptable range.’ if x < 20 or x > 40: print ‘The value is outside the acceptable range.’ # This is an error! if x < 20 and x > 40: print ‘The value is outside the acceptable range.’
4-23
Boolean Variables Concept: A Boolean variable can reference one of two values: True or False. Boolean variables are commonly used as flags, which indicate whether a specific condition exists.
4-24
Boolean Variables
if sales_quota_met == True:
print ‘You have met your sales quota!.’ if sales_quota_met: print ‘You have met your sales quota!.’ OR
if sales >= 50000: sales_quota_met = True
else:
sales_quota_met = False
- Match Case in Python version 3.0 1-25
AnyQuestion?
Repetition Structures
5-28
- Introduction to Repetition Structures
Concept: The repetition structure causes a statement or set of statements to execute repeatedly.
5-29
Introduction to Repetition Structures Condition-Controlled and Count-Controlled Loops A condition-controlled loop uses a true/false condition to control the number of times that it repeats. A count-controlled loop repeats a specific number of times.
5-30
The while Loop: a Condition-Controlled Loop Concept: A condition-controlled loop causes a statement or set of statements to repeat as long as a condition is true. In Python you use the while statement to write a condition-controlled loop.
5-31
The while Loop: a Condition-Controlled Loop In Python … while condition: statement statement etc. The logic of a while loop
5-32
The while Loop: a Condition-Controlled Loop The while Loop is a Pretest Loop, which means it tests its condition before performing an iteration.
5-33
The for Loop: a Count-Controlled Loop Concept: A count-controlled loop iterates a specific number of times. In Python you use the for statement to write a count-controlled loop.
5-34
The for Loop: a Count-Controlled Loop In Python … for variable in [value1, value2, etc.]: statement statement etc.
5-35
The for Loop: a Count-Controlled Loop Using the range Function with the for Loop for num in [0, 1, 2, 3, 4]: print num for num in range(5): print num
5-36
The for Loop: a Count-Controlled Loop Using the range Function with the for Loop
- First argument, 1, is the starting value for the list
- Second argument, 10, is the ending limit of the list
- Third argument, 2, is the step value for num in range(1, 10, 2): print num
5-37
The for Loop: a Count-Controlled Loop Generating Lists that Range from Highest to Lowest for num in range(5, 0, -1): print num
5-38
The Augmented Assignment Operators The Augmented Assignment Operators Table 5-2 The age variable references the value 25
5-39
Input Validation Loops Concept: Input validation is the process of inspecting data that has been input to a program, to make sure it is valid before it is used in a computation. Input validation is commonly done with a loop that iterates as long as an input variable references bad data.
5-40
Input Validation Loops Error Trap or Error Handler
- 5-41
- Input Validation Loops
- Priming Read
- # Get a test score.
- Score = input(‘Enter a test score: ‘)
5-41
Input Validation Loops Priming Read # Get a test score.
Score = input(‘Enter a test score: ‘)
# Make sure it is not less than 0. while score < 0: print ‘ERROR: The score cannot be negative.’
score = input (‘Enter the correct score: ‘) 5-42
Nested Loops Concept: A loop that is inside another loop is called a nested loop.
5-43
Nested Loops About Nested Loops:
- The inner loop goes through all of its iterations for every single iteration of the outer loop
- Inner loops complete their iterations faster than outer loops for hours in range(24): for minutes in range(60): for seconds in range(60): print hours, ‘:’, minutes, ‘:’, seconds
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
QUESTIONS
? Repetition Structures
8-45
- Processing Lists with control structure
Processing Lists: Totaling the Values in a List Program 8-16 (total_list.py)
8-46
Processing Lists with control structure Averaging the Values in a List Program 8-17 (average_list.py)
Processing Lists with control structure
1-47
Search a Value in a List
Menu -1
1-48
How the Menu System Works
- The program uses a menu-driven approach to control execution.
- A Main Menu is displayed inside a while loop and repeats until the user selects Exit.
- User input is validated using read_integer_in_range.
- The program uses match / case to decide which function to run.
- A Sub Menu (List Processing Menu) works the same way:
- It has its own loop.
- Each option calls a separate function.
- Choosing “Return to Main Menu” exits the sub menu.
- Input functions are stored in a separate file, keeping the menu logic clean and easy to read. =============================== # Main Menu # =============================== def main(): finished = False while finished == False: print("\nMain Menu:") print("1 List Processing") print("2 Other Feature") print("3 Exit") choice = input_functions.read_integer_in_range("Please enter your choice:", 1, 3) match choice: case 1: list_processing_menu() case 2: other_feature() case 3: finished = True case _: print("Please select again") main()
Menu -2
1-49
import input_functions
# ===============================
# List Processing Sub Menu
# ===============================
def list_processing_menu():
finished = False while finished == False:
print("\nList Processing Menu:") print("1 Enter a list") print("2 Calculate total") print("3 Calculate average") print("4 Search in list") print("5 Return to Main Menu")
choice =
input_functions.read_integer_in_range("Please enter your choice:", 1, 5) match choice: case 1: enter_list() case 2: calculate_total() case 3: calculate_average() case 4: search_item() case 5:
finished = True
case _: print("Please select again")
# ===============================
# Stub functions (EXPLANATION ONLY)
# ===============================
def enter_list(): print("This is the code for ENTERING a list.") input("Press Enter to continue") def calculate_total(): print("This is the code for CALCULATING the total of a list.") input("Press Enter to continue") def calculate_average(): print("This is the code for CALCULATING the average of a list.") input("Press Enter to continue") def search_item(): print("This is the code for SEARCHING an item in a list.") input("Press Enter to continue")
# ===============================
# Option 2 – Other Feature (Stub)
# ===============================
def other_feature(): print("This is the code for OPTION 2 in the Main Menu.") input("Press Enter to continue")
1-50 # ===============================
# Main Menu (Ruby-style)
# ===============================
def main():
finished = False while finished == False:
print("\nMain Menu:") print("1 List Processing") print("2 Other Feature") print("3 Exit")
choice = input_functions.read_integer_in_range("Please enteryour choice:", 1, 3) match choice: case 1: list_processing_menu() case 2: other_feature() case 3:
finished = True
case _: print("Please select again") main()
1-51
import input_functions
# ===============================
# Input list function
# ===============================
def input_number_list():
numbers = []
count = input_functions.read_integer_in_range("How manynumbers do you want to enter?", 1, 100) while i < count:
value = float(input(f"Enter number {i + 1}: "))numbers.append(value) return numbers
# ===============================
# Processing functions # (return only, no print)
# ===============================
def total_list(numbers): while i < len(numbers):
total += numbers[i]
return total def average_list(numbers): return total_list(numbers) / len(numbers) def search_list(numbers, target): while i < len(numbers):
if numbers[i] == target:
return True return False
Process List(full code) with Menu -3
1-52 # ===============================
# List Processing Sub Menu
# ===============================
def list_processing_menu():
finished = False numbers = [] while finished == False:
print("\nList Processing Menu:") print("1 Enter a list of numbers") print("2 Calculate total of the list") print("3 Calculate average of the list") print("4 Search for a value in the list") print("5 Return to Main Menu")
choice = input_functions.read_integer_in_range("Pleaseenter your choice:", 1, 5) match choice: case 1:
numbers = input_number_list()
case 2:
if len(numbers) == 0:
print("The list is empty. Please enter a list first.") else: print("The total of the elements is", total_list(numbers)) input("Press Enter to continue") case 3:
if len(numbers) == 0:
print("The list is empty. Please enter a list first.") else: print("The average of the elements is", average_list(numbers)) input("Press Enter to continue") case 4:
if len(numbers) == 0:
print("The list is empty. Please enter a list first.") else:
value = float(input("Enter a value to search for:")) if search_list(numbers, value): print(value, "was found in the list.") else: print(value, "was not found in the list.") input("Press Enter to continue") case 5:
finished = True
case _: print("Please select again")
# ===============================
# Option 2 – Other Feature (Stub)
# ===============================
def other_feature(): print("You selected Option 2 (Other Feature).") input("Press Enter to return to the Main Menu")
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
QUESTIONS
?
Recap
- Whatisint h i sl e s s o n?
- The Decision Structure
- The Relational Operators
- The if Statement
- The if-else Statement
- Logical Operators
- The Match Case in Python version 3.0
- Introduction to Repetition Structures
- The while Loop
- The for Loop:
- Processing List with Menu 1-54
1-55