๐ค What is a Condition?
A condition is a yes/no question your program asks to decide what to do next. If the answer is True, run one block of code. If False, run another โ or skip it entirely.
In plain English: check whether something is true, then act accordingly. Conditions are the heartbeat of every program: credit checks, eligibility gates, error handling, game logic, recommendation filters.
๐ฏ Comparison & Logical Operators
๐ฆ The Business Scenario
SouthBank India in Mumbai processes thousands of loan applications daily. Each applicant has a credit score, annual income, and employment status. The bank approves based on rules: score above 700, income above โน400,000, and employed status. Let's code this decision logic.
๐ป Step 1: Simple Credit Score Check
Start with a single condition: does the applicant's credit score meet the minimum?
๐ Step 2: Loan Tiers with elif
Now check all three criteria and assign a loan tier. Use elif โ "else if" โ to chain multiple conditions without redundant checks.
โ๏ธ Step 3: Flat vs Nested Conditionals
Avoid deeply nested if-else chains โ they become hard to read and debug. Flatten them using and / or logic.
โก Step 4: Ternary Expressions (One-Liners)
For simple if/else, use a ternary: x if condition else y. It's concise and Pythonic.
๐ Also Used In
Conditional Logic Across Domains
๐ค AI & Machine Learning Connection
Every decision a machine learning model makes is a conditional. When a fraud detection model flags a โน50,000 transaction as suspicious, it's running an if/else chain: if (score > threshold) and (unusual_amount) and (new_merchant), then flag. The training process learns the best thresholds and rules. You're writing the human-readable version.
๐ฏ Mini Challenge
Write a program that takes age and purchase_amount, then applies a discount: under 18 gets 10%, 18โ65 gets 5%, over 65 gets 15%. Use if/elif/else or ternary. Print the original, discount, and final amount.
if age < 18: discount = 0.10, then elif age <= 65: discount = 0.05, else discount = 0.15. Then final = purchase_amount * (1 - discount). Or use ternary: discount = 0.10 if age < 18 else (0.05 if age <= 65 else 0.15).
๐ค Interview Questions
if starts a new condition block. elif ("else if") is only checked if the previous if was false. Once any branch executes, the rest are skipped. Use if for independent checks; use elif for mutually exclusive conditions (loan tiers, age brackets).False, 0, 0.0, "" (empty string), [], {}, None. Truthy: everything else. So if items: is true if items is a non-empty list; if balance: is false if balance is 0. This is a shortcut: if len(items) > 0: can become if items:.elif when the conditions are mutually exclusive (a person is either under 18, 18โ65, or over 65 โ not two at once). Use multiple if statements when each condition is independent. Example: multiple if for alerts (if balance_low: ... if fraud_flag: ...) โ both can be true. Use elif for tiers (only one applies).a and b, if a is false, Python doesn't evaluate b โ it skips straight to false. In a or b, if a is true, b is skipped. This saves CPU. Example: if user and user.is_admin: โ if user is None (falsy), the second part won't run and won't crash. Without short-circuit, None.is_admin would throw an error.and / or to combine conditions upfront. Name intermediate booleans for clarity: is_eligible = emp and score >= 700, then if is_eligible:. Avoid 3+ levels of indentation. Use guard clauses: if not condition: return early, leaving the main logic unindented. This is the single biggest anti-pattern beginners fall into โ learn to refactor it now.๐ง Quick Quiz
5 > 3 evaluate to?x == 5 and y == 10 to be true?x = 0
if x: print("True")
else: print("False")if x > 10: y = "big"
else: y = "small"?score = 750
if score >= 750: print("Gold")
elif score >= 700: print("Silver")
else: print("None")๐ Quick Cheatsheet
| Pattern | Code | When to Use |
|---|---|---|
| Simple if | if x > 5: print("big") | Single condition, no alternative |
| if/else | if x > 5: print("big") | Two mutually exclusive paths |
| if/elif/else | if x > 10: t="big" | 3+ mutually exclusive conditions |
| Multiple if | if x: do_a() | Independent checks (both can be true) |
| Ternary | z = "yes" if x else "no" | One-liner if/else assignment |
| Short-circuit | if x and x.attr: | Avoid error if x is None/falsy |
โ ๏ธ Common Mistakes
== instead of = (and vice versa)= assigns a value. == compares. In an if condition, always use ==. Wrong: if x = 5: (assigns x). Right: if x == 5: (checks equality).and / or and intermediate booleans. Instead of checking one condition at a time, combine them: if emp and score >= 700 and inc >= 400000: instead of three nested ifs.if x == Trueif x:, not if x == True:. It's shorter and more Pythonic. Same for if not x: instead of if x == False:.:. No exception. Python uses the colon to signal the start of an indented block.โฆ Key Takeaways
- Conditions ask yes/no questions; use comparison operators
<,>,==,!=,<=,>= andrequires all conditions true;orrequires at least one true;notinverts- Use
ifto start;eliffor mutually exclusive alternatives;elseas the final fallback - Avoid deeply nested if-else โ flatten with
and/orand named booleans - Truthy values: non-zero, non-empty; falsy: 0, "", [], {}, None โ use directly in conditions
- Ternary
x if condition else yis a one-liner for simple if/else assignments
Ready to master conditionals in real apps?
Join the Best AI Program: The AI-Era Analyst โ 5 months, fully online, with placement assistance. Week 1 is free.
Explore The AI-Era Analyst โ