Python Coding Day 7 | Nested if, elif (Else If), Logical Operators

Nested if, elif (Else if), Logical Operators

Watch the lesson tutorial  ðŸ”»


1. Nested if Statements

A nested if statement is an if statement inside another if or else statement. This structure allows you to check for a primary condition and then, only if the primary condition is true, check for one or more secondary, more specific conditions.

This is useful when the validity of a secondary condition logically depends on a broader, preceding condition.

Practical Example: Nested if for Admission

Imagine a program checking if a student is eligible for a special program. They must first be a senior, and then they must have a GPA above a certain threshold.

Python
# Variables
student_status = "Senior"
gpa = 3.8

# Primary check: Is the student a Senior?
if student_status == "Senior":
    print("Primary check passed: Student is a Senior.")
    
    # Nested check: Is the GPA high enough?
    if gpa >= 3.5:
        print("Nested check passed: GPA is 3.8.")
        print("The student is eligible for the Honors Program.")
    else:
        print("Nested check failed: GPA is too low.")
        print("The student is not eligible for the Honors Program.")
        
else:
    print("Primary check failed: Student must be a Senior to be considered.")
    
# Output in this case:
# Primary check passed: Student is a Senior.
# Nested check passed: GPA is 3.8.
# The student is eligible for the Honors Program.

2. The elif (Else If) Statement

The elif statement (short for "else if") allows you to check multiple alternative conditions sequentially.

In a sequence of if-elif-else:

  1. The first if condition is checked.

  2. If the if condition is False, the first elif is checked.

  3. If that elif is False, the next elif is checked, and so on.

  4. The first condition that evaluates to True is executed, and the rest of the structure is skipped.

  5. If none of the if or elif conditions are true, the final else block (if present) is executed.

This is highly efficient for handling mutually exclusive scenarios.

Practical Example: elif for Grading System

Let's use elif to determine a letter grade based on a score, where only one grade can be assigned.

Python
# Variable
score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")

# Output in this case:
# Grade: B

💡 Key Takeaway: The score 85 is technically $>=$ 60 and $>=$ 70, but because the score >= 80 condition was met first, the Grade: B block executes, and the program skips checking for C, D, or F.


3. Logical Operations: NOT, AND, OR

Logical operations are used to combine or modify boolean (True/False) conditions, allowing you to create more complex conditional expressions.

A. The AND Operator

  • Explanation: The AND operator requires both conditions to be True for the entire expression to be True. If even one condition is False, the result is False.

  • Use Case: When an action requires fulfilling multiple criteria simultaneously.

Condition 1Condition 2Result (C1 AND C2)
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse
  • Practical Example: AND for Discount Eligibility

Python
is_member = True
total_purchase = 150

# Condition: Must be a member AND purchase must be over $100
if is_member and total_purchase > 100:
    print("Eligible for a 20% member discount!")
else:
    print("Not eligible for the member discount.")
    
# Output in this case:
# Eligible for a 20% member discount!

B. The OR Operator

  • Explanation: The OR operator requires at least one condition to be True for the entire expression to be True. It is only False if both conditions are False.

  • Use Case: When an action can be triggered by meeting one of several acceptable criteria.

Condition 1Condition 2Result (C1 OR C2)
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse
  • Practical Example: OR for Login Access

Python
username_match = False
password_match = True

# Condition: Access is granted if EITHER the username OR password matches (or both).
if username_match or password_match:
    print("Authentication successful. Logging in...")
else:
    print("Authentication failed. Access denied.")

# Output in this case:
# Authentication successful. Logging in...

C. The NOT Operator

  • Explanation: The NOT operator reverses a boolean value. If a condition is True, NOT makes it False, and if it's False, NOT makes it True.

  • Use Case: To check for the absence of a condition, or to write code that executes when a condition is not met.

ConditionResult (NOT Condition)
TrueFalse
FalseTrue
  • Practical Example: NOT for Inventory Check

Python
is_in_stock = False

# Condition: Execute block if the item is NOT in stock
if not is_in_stock:
    print("Item is out of stock. Trigger restock order.")
else:
    print("Item is in stock.")
    
# Output in this case:
# Item is out of stock. Trigger restock order.

- by Chirana Nimnaka


Comments

Popular posts from this blog

Python Coding Day 1 | The print() Function and Comments

What is Python?

Set Up an Environment to Code in Python