Python If Else: Conditional Logic for AI & ML

Master Python's 'if', 'if-else', and 'if-elif-else' statements for building smart AI and ML applications. Control program flow with Python conditionals.

Python Conditional Statements: if, if-else, and if-elif-else

In Python, conditional statements, also known as control flow statements, are fundamental for making decisions within your programs. They allow you to execute specific blocks of code only when certain conditions are met, enabling dynamic and responsive behavior.


1. Basic if and if-else Statements

The if Statement

The if statement is used to execute a block of code only if a specified condition evaluates to True. If the condition is False, the code within the if block is skipped.

Syntax:

if condition:
    # Code to execute if the condition is True
    # This block is indented

The if-else Statement

The if-else statement provides a two-way branching mechanism. It allows you to execute one block of code if the condition is True and a different block of code if the condition is False.

Syntax:

if condition:
    # Code to execute if the condition is True
    # This block is indented
else:
    # Code to execute if the condition is False
    # This block is also indented

How if-else Works:

  1. Python evaluates the condition after the if keyword.
  2. If the condition evaluates to True, the code block indented under the if statement is executed.
  3. If the condition evaluates to False, the code block indented under the else statement is executed.
  4. After the if-else block is processed, the program continues execution with the next statement following the block.

Example:

age = 17
print(f"Age: {age}")

if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote yet.")

Sample Output:

Age: 17
You are not eligible to vote yet.

Try changing the age variable to 20 to observe how the program's output changes.


2. The if-elif-else Statement

When you need to check multiple conditions in a specific order, using multiple if-else statements or deeply nested if blocks can quickly become complex and hard to read. Python's elif (short for "else if") statement provides a clean and structured way to handle such scenarios.

Why Use elif?

The elif statement allows you to check additional conditions sequentially after the initial if condition. This makes your code more readable and maintainable when dealing with more than two possible outcomes.

Syntax:

if condition1:
    # Code to execute if condition1 is True
elif condition2:
    # Code to execute if condition1 is False and condition2 is True
elif condition3:
    # Code to execute if condition1 and condition2 are False, and condition3 is True
# ... you can add more elif statements as needed
else:
    # Code to execute if none of the above conditions are True (optional)

How if-elif-else Works:

  1. Python evaluates condition1 in the if statement.
  2. If condition1 is True, the corresponding code block is executed, and the rest of the elif and else blocks are skipped.
  3. If condition1 is False, Python moves to the first elif statement and evaluates condition2.
  4. If condition2 is True, its code block is executed, and the remaining elif and else blocks are skipped.
  5. This process continues for all elif conditions.
  6. If none of the if or elif conditions evaluate to True, and an else block is present, the code within the else block is executed.

Real-World Example: Discount Calculator

Let's simulate a retail discount system based on the total purchase amount:

  • Spend over ₹10,000: Get a 20% discount
  • Spend between ₹5,001 and ₹10,000: Get a 10% discount
  • Spend between ₹1,001 and ₹5,000: Get a 5% discount
  • Spend ₹1,000 or less: No discount

Code Example:

amount = 7500
print(f"Total amount: {amount}")

discount = 0
if amount > 10000:
    discount = amount * 0.20
    print("Discount applied: 20%")
elif amount > 5000:
    discount = amount * 0.10
    print("Discount applied: 10%")
elif amount > 1000:
    discount = amount * 0.05
    print("Discount applied: 5%")
else:
    print("No discount applied.")

payable = amount - discount
print(f"Discount amount: {discount}")
print(f"Final amount to pay: {payable}")

Sample Outputs for Different Amounts:

Amount (₹)Discount AppliedDiscount Amount (₹)Final Payable Amount (₹)
800010%800.07200.0
25005%125.02375.0
750No discount0.0750.0
1500020%3000.012000.0

Avoiding Deep Nesting with elif

Consider the following nested if structure, which can become difficult to follow:

# Less readable example with nested ifs
if condition1:
    # do something
else:
    if condition2:
        # do something else
    else:
        if condition3:
            # do yet another thing
            pass # placeholder

The if-elif-else structure offers a much cleaner alternative for handling multiple conditions, promoting better code organization and readability:

# More readable example with if-elif-else
if condition1:
    # do something
elif condition2:
    # do something else
elif condition3:
    # do yet another thing
else:
    # handle the default case
    pass # placeholder

Summary Table: Python Conditional Structures

StructurePurpose
ifExecutes a block if a condition is True.
if-elseProvides two-way decision-making.
if-elif-elseHandles multiple conditions in a structured way.

Conclusion

Mastering conditional statements (if, if-else, if-elif-else) is crucial for implementing decision logic in your Python programs. These structures empower you to control program flow based on various conditions, whether you're validating user input, applying business rules, or branching logic based on data.


SEO Keywords

Python conditional statements, if else in Python, Python if elif else, control flow in Python, decision making in Python, Python if statement example, Python nested if else, real-world if else example Python, Python elif usage, Python discount calculator example.


Interview Questions

  1. What is a conditional statement in Python?
  2. Explain the difference between if, if-else, and if-elif-else.
  3. Can you write a Python program to check if a number is positive, negative, or zero?
  4. How does the elif statement improve code readability?
  5. What happens if multiple elif conditions are true in Python?
  6. How does Python decide which block to execute in an if-elif-else structure?
  7. Write a Python program to calculate a discount based on the purchase amount using if-elif-else.
  8. What is the difference between using multiple if statements and an if-elif-else ladder?
  9. Can we use logical operators like and, or, not in if statements? Provide an example.
  10. What will happen if none of the conditions in if-elif-else are true and there’s no else block?