Lesson 4.4: Selection and Iteration
Introduction
In this lesson, students, we will explore the fundamental concepts of selection and iteration in programming. These concepts are crucial as they allow your programs to make decisions and repeat actions, which is essential for creating dynamic and responsive applications. By the end of this lesson, you will understand how to use Boolean expressions and comparison operators, how to structure if statements, and how to implement loops effectively in Python. Let's dive in!
Objectives
- Understand Boolean expressions and comparison operators.
- Learn about if, if-else, and if-elif-else structures.
- Combine conditions using logical operators: and, or, and not.
- Differentiate between definite iteration with for loops and indefinite iteration with while loops.
- Implement loop controls to manage iteration properly.
Selection Statements
Boolean Expressions and Comparison Operators
A Boolean expression is an expression that evaluates to either True or False. In programming, Boolean expressions are fundamental because they are used to control the flow of code execution.
Comparison operators are usually used to form Boolean expressions. Here are the most common comparison operators in Python:
- Equal to:
== - Not equal to:
!= - Greater than:
> - Less than:
< - Greater than or equal to:
>= - Less than or equal to:
<=
Example 1: Using Comparison Operators
Let's say we have two variables, a and b:
a = 10
b = 20
We can create several Boolean expressions using comparison operators:
a == bwhich evaluates toFalsea < bwhich evaluates toTruea != bwhich evaluates toTrue
These expressions can be used to control the flow of the program.
If Statements
The simplest form of selection in Python is the if statement. It allows you to execute a block of code only if a specified condition is True.
Syntax:
if condition:
# code to execute if condition is true
Example 2: Basic If Statement
Let's write an if statement to check if a number is positive:
number = 5
if number > 0:
print("The number is positive.")
In this case, the output will be The number is positive. since 5 is indeed greater than 0.
If-Else Statements
Sometimes, you need to specify an alternative action if the condition is not met. This is where the if-else statement comes in.
Syntax:
if condition:
# code to execute if condition is true
else:
# code to execute if condition is false
Example 3: If-Else Statement
Consider the following example that checks if a number is even or odd:
number = 10
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Since 10 is even, the output will be The number is even.
If-Elif-Else Chain
For multiple conditions, the if-elif-else structure can be used. This allows you to check several possibilities in a clear manner.
Syntax:
if condition1:
# code for condition1
elif condition2:
# code for condition2
...
else:
# code if none of the conditions are true
Example 4: If-Elif-Else Statement
Let's classify a student's grade based on their score:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")
This will output Grade: B because 85 is between 80 and 90.
Logical Operators
Logical operators allow you to combine multiple Boolean expressions. In Python, there are three main logical operators:
- and: Returns
Trueif both operands are true. - or: Returns
Trueif at least one operand is true. - not: Reverses the Boolean value.
Example 5: Using Logical Operators
Consider the following code where we check if a number is between 10 and 20:
number = 15
if number >= 10 and number <= 20:
print("The number is between 10 and 20.")
This will print The number is between 10 and 20. since both conditions are true.
Iteration
Iteration allows you to execute a block of code multiple times. There are two primary types of iteration structures in Python: definite iteration (using for loops) and indefinite iteration (using while loops).
For Loops
A for loop is used when you know exactly how many times you want to iterate over a sequence, like a list or a string.
Syntax:
for item in sequence:
# code to execute for each item
Example 6: For Loop
Here’s an example that prints each character in a string:
word = "Python"
for char in word:
print(char)
The output will be:
P
y
t
h
o
n
While Loops
A while loop continues to execute as long as a condition is True. It is used when the number of iterations is not known ahead of time.
Syntax:
while condition:
# code to execute while condition is true
Example 7: While Loop
Here’s an example that uses a while loop to count down:
count = 5
while count > 0:
print(count)
count -= 1
The output will be:
5
4
3
2
1
Loop Control
Within loops, you may want to control how the iteration proceeds. Here are some common mechanisms:
Accumulators and Counters
An accumulator is a variable that keeps a running total, while a counter keeps track of how many times something has occurred.
Example 8: Using an Accumulator and a Counter
Let’s say we want to sum numbers from 1 to 5:
sum = 0
for i in range(1, 6):
sum += i
print("Sum from 1 to 5 is:", sum)
The output will be Sum from 1 to 5 is: 15.
Early Exit with Break
You can exit a loop using the break statement. This is useful when you want to stop the loop when a certain condition is met.
Example 9: Break Statement
for i in range(10):
if i == 5:
break
print(i)
This will output:
0
1
2
3
4
Avoiding Infinite Loops
An infinite loop occurs when the condition for the loop never becomes false, causing it to run indefinitely. Always ensure that your loop has a way to terminate.
Conclusion
In this lesson, students, we covered essential concepts in selection and iteration. We learned how Boolean expressions and comparison operators work alongside selection statements (if, if-else, if-elif-else) to control the flow of a program. Additionally, we discussed how to implement loops effectively with for and while, and how to use loop control techniques. Mastering these concepts sets the foundation for more advanced programming techniques.
Study Notes
- Boolean expressions evaluate to
TrueorFalse. - Comparison operators include
==,!=,>,<,>=, and<=. - Use
if,if-else, andif-elif-elsefor conditional statements. - Logical operators
and,or, andnotare used to combine conditions. - Definite iteration is done with
forloops, while indefinite iteration is handled withwhileloops. - Use counters for counting iterations and accumulators for summing values.
- Use
breakto exit loops early and ensure conditions are well-defined to avoid infinite loops.
