๐Ÿค” 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.

if condition: (do this)

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

==
x == 5
Equal to โ€” both sides have the same value
!=
x != 5
Not equal to โ€” different values
<
x < 5
Less than โ€” left is smaller
>
x > 5
Greater than โ€” left is bigger
<=
x <= 5
Less than or equal
>=
x >= 5
Greater than or equal
and
a and b
Both must be True
or
a or b
At least one must be True
not
not x
Flip the boolean

๐Ÿฆ The Business Scenario

๐Ÿฆ
Banking ยท SouthBank India
Automated Loan Approval System

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.

3
Decision criteria
2
Loan tiers
<1ms
Approval time

๐Ÿ’ป Step 1: Simple Credit Score Check

Start with a single condition: does the applicant's credit score meet the minimum?

loan_check_v1.py โ–ถ Run to see output below
# Output โœ“ Credit score approved: 720 โœ“ Employed status: Active

๐Ÿ”„ 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.

loan_check_v2.py โ–ถ Common interview pattern
# Output โœ“ APPROVED: Silver Tier (Max โ‚น2,50,000)

โš™๏ธ 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.

nested_refactor.py โ–ถ Best practice
# Output Loan tier: Silver

โšก Step 4: Ternary Expressions (One-Liners)

For simple if/else, use a ternary: x if condition else y. It's concise and Pythonic.

ternary_shipping.py โ–ถ Real e-commerce use case
# Output City: Nairobi, Weight: 2.5kg, Order: KSh15000 Shipping fee: KSh50

๐ŸŒ Also Used In

Conditional Logic Across Domains

๐Ÿ“ฑ
if balance >= top_up_amount: refill()
Telecom โ€” auto-recharge when balance drops below threshold
๐Ÿฅ
if age > 65 and condition == "chronic": priority_queue()
Healthcare โ€” triage patients by age and severity
๐Ÿ›’
if stock == 0 or supplier_delay: notify_customer()
E-commerce โ€” backorder alerts, inventory gates
๐Ÿค–
if prediction_score > threshold and not noise: classify()
ML โ€” confidence thresholds, spam detection, anomaly gates

๐Ÿค– 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.

decision trees if-else thresholds rule-based systems binary classification

๐ŸŽฏ Mini Challenge

Build an Age-Based Discount Calculator

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.

Start with 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).
Falsy: 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:.
Use 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).
In 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.
Use 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

Question 1 of 5
What does 5 > 3 evaluate to?
Question 2 of 5
Which condition must be true for x == 5 and y == 10 to be true?
Question 3 of 5
What does the following code print?
x = 0
if x: print("True")
else: print("False")
Question 4 of 5
Which is equivalent to if x > 10: y = "big"
else: y = "small"
?
Question 5 of 5
In the code below, what prints?
score = 750
if score >= 750: print("Gold")
elif score >= 700: print("Silver")
else: print("None")
0
/5

๐Ÿ“‹ Quick Cheatsheet

PatternCodeWhen to Use
Simple ifif x > 5: print("big")Single condition, no alternative
if/elseif x > 5: print("big")
else: print("small")
Two mutually exclusive paths
if/elif/elseif x > 10: t="big"
elif x > 5: t="medium"
else: t="small"
3+ mutually exclusive conditions
Multiple ifif x: do_a()
if y: do_b()
Independent checks (both can be true)
Ternaryz = "yes" if x else "no"One-liner if/else assignment
Short-circuitif x and x.attr:Avoid error if x is None/falsy

โš ๏ธ Common Mistakes

Using == 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).
Deeply nested if-else (3+ levels)
Refactor using 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.
Redundant comparisons like if x == True
Write if x:, not if x == True:. It's shorter and more Pythonic. Same for if not x: instead of if x == False:.
Forgetting the colon after if/elif/else
Every if, elif, else, for, while, def, class must end with :. No exception. Python uses the colon to signal the start of an indented block.

โœฆ Key Takeaways

  • Conditions ask yes/no questions; use comparison operators <, >, ==, !=, <=, >=
  • and requires all conditions true; or requires at least one true; not inverts
  • Use if to start; elif for mutually exclusive alternatives; else as the final fallback
  • Avoid deeply nested if-else โ€” flatten with and / or and named booleans
  • Truthy values: non-zero, non-empty; falsy: 0, "", [], {}, None โ€” use directly in conditions
  • Ternary x if condition else y is a one-liner for simple if/else assignments
Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

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 โ†’