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:
- Python evaluates the
condition
after theif
keyword. - If the
condition
evaluates toTrue
, the code block indented under theif
statement is executed. - If the
condition
evaluates toFalse
, the code block indented under theelse
statement is executed. - 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:
- Python evaluates
condition1
in theif
statement. - If
condition1
isTrue
, the corresponding code block is executed, and the rest of theelif
andelse
blocks are skipped. - If
condition1
isFalse
, Python moves to the firstelif
statement and evaluatescondition2
. - If
condition2
isTrue
, its code block is executed, and the remainingelif
andelse
blocks are skipped. - This process continues for all
elif
conditions. - If none of the
if
orelif
conditions evaluate toTrue
, and anelse
block is present, the code within theelse
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 Applied | Discount Amount (₹) | Final Payable Amount (₹) |
---|---|---|---|
8000 | 10% | 800.0 | 7200.0 |
2500 | 5% | 125.0 | 2375.0 |
750 | No discount | 0.0 | 750.0 |
15000 | 20% | 3000.0 | 12000.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
Structure | Purpose |
---|---|
if | Executes a block if a condition is True . |
if-else | Provides two-way decision-making. |
if-elif-else | Handles 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
- What is a conditional statement in Python?
- Explain the difference between
if
,if-else
, andif-elif-else
. - Can you write a Python program to check if a number is positive, negative, or zero?
- How does the
elif
statement improve code readability? - What happens if multiple
elif
conditions are true in Python? - How does Python decide which block to execute in an
if-elif-else
structure? - Write a Python program to calculate a discount based on the purchase amount using
if-elif-else
. - What is the difference between using multiple
if
statements and anif-elif-else
ladder? - Can we use logical operators like
and
,or
,not
inif
statements? Provide an example. - What will happen if none of the conditions in
if-elif-else
are true and there’s noelse
block?
Python Control Statements: Master Program Flow for AI
Learn Python control statements like if, elif, and else to manage program flow, essential for building robust AI and machine learning applications.
Python Loops: Automate Tasks & Data Processing
Master Python loops for efficient code execution. Learn to automate repetitive tasks and process data collections with loops, a core concept in programming.