Lecture05-1
Lecture05-1
1 Introduction
In Python, conditional statements allow you to execute certain blocks of code
based on whether a condition is true or false. The primary conditional structures
are:
These structures can be applied to various data types, including strings and
lists. This document explains how to use these structures effectively in Python
with examples involving strings and lists.
2.2 Code
The following code demonstrates how to use a basic if-else statement to check
the condition:
1. word = "hello"
2. if word == "hello":
3. print("The word is hello!")
4. else:
5. print("The word is not hello.")
1
2.3 Explanation
In this example:
3.2 Code
The following code demonstrates how to use elif to check multiple conditions:
1. word = "apple"
2. if word == "banana":
3.3 Explanation
In this case:
If neither condition is true, the else block executes and prints the message
that the word is neither ”banana” nor ”apple”.
2
4 Example with Lists
4.1 Problem Description
You are given a list of fruits, fruits, and a string variable fruit. You need
to check if fruit is in the list fruits. If it is, print a message saying that the
fruit is in the list. If it is not, print a message saying that the fruit is not in the
list.
4.2 Code
The following code demonstrates how to use in with an if-else statement to
check membership in a list:
3. if fruit in fruits:
4. print(f"fruit is in the list of fruits.")
5. else:
6. print(f"fruit is not in the list of fruits.")
4.3 Explanation
In this case:
The if statement checks if fruit is present in the list fruits.
If the fruit is found in the list, the first block of code executes, printing
that the fruit is in the list.
Otherwise, the else block executes and prints that the fruit is not in the
list.
3
5.2 Code
The following code demonstrates how to use multiple elif statements with a
list:
3. if fruit == "apple":
4. print("Apple is in the list.")
5. elif fruit == "banana":
5.3 Explanation
In this example:
If none of these conditions are true, the else block prints that the fruit is
not in the list.
4
6.2 Code
The following code demonstrates how to combine conditions using and:
6.3 Explanation
Here:
The condition fruit in fruits checks if fruit is in the list fruits.
The condition color == "yellow" checks if the color is ”yellow”.
The and operator ensures that both conditions must be true for the first
block to execute. If either condition is false, the else block executes.
7.2 Code
The following code demonstrates how to nest if statements:
5
7. else:
8. print(f"fruit is not yellow.")
9. else:
7.3 Explanation
In this example:
8 Conclusion
In this document, we explored the if, elif, and else conditional structures in
Python, with examples using strings and lists. These structures are crucial for
controlling the flow of a program and are versatile for handling various types of
conditions in Python.