Fall 2024 - P3
3.8.5 Nested If Statements
Learn what a nested if statement is and does, practice problems for getting familiar with nested if statements
Basic Overview:
- A nested if statement is an if statement placed inside another if, else if, or even a loop.
- You can use nested if statements inside a for loop to perform multiple condition checks.
- A for loop iterates through a collection (like a list) and checks various conditions using if statements in each iteration.
- Based on the condition results, the corresponding code is executed.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num % 2 == 0: # Check if the number is even
if num > 5: # Another condition inside the first if statement
print(num, "is even and greater than 5")
else:
print(num, "is even and less than or equal to 5")
else: # If it's not even, it must be odd
print(num, "is odd")
1 is odd
2 is even and less than or equal to 5
3 is odd
4 is even and less than or equal to 5
5 is odd
6 is even and greater than 5
7 is odd
8 is even and greater than 5
9 is odd
10 is even and greater than 5
Practice Problem
- Here, there are four numbers listed. Using your knowledge of nested if statements, write code that will print the positive numbers in one group and the negative numbers as one group.
- Helpful Hint: the command that checks if a number is negative is “if num<0”
# List of numbers
numbers = [10, -5, 7, -3]
# Your task: Write a loop with nested if statements to print whether each number is positive or negative
# <h2> Answer to the Practice Problem </h2>
numbers = [0, -3, 5, -8, 2, 0, 7, -1]
for num in numbers:
if num == 0: # Check if the number is zero
print(num, "is zero")
else:
if num > 0: # Check if the number is positive
if num % 2 == 0: # Nested if to check if it's even
print(num, "is positive and even")
else: # If it's not even, it must be odd
print(num, "is positive and odd")
else: # If it's not positive, it must be negative
print(num, "is negative")
0 is zero
-3 is negative
5 is positive and odd
-8 is negative
2 is positive and even
0 is zero
7 is positive and odd
-1 is negative
What is Happening:
- The code loops through a list of numbers.
- For each number, it first checks if the number is even.
- If even, it checks if the number is greater than 5.
- If the number is not greater than 5, it prints that it is even and ≤ 5.
- If the number is odd, it simply prints that the number is odd.
Additional Notes:
- Multiple Conditions: Nested if statements allow you to add layers of condition checks, which is helpful when you want to ensure that several criteria are met before executing certain code.
- Code Readability: While nested if statements provide flexibility, too many levels of nesting can make the code harder to read. Always try to keep nesting simple and clear.
- Real-World Use: Nested if statements are commonly used in scenarios where decisions need to be made based on multiple criteria, such as filtering or categorizing data.