Python 3.12+ Python Fundamentals Data Analytics Core

Python Conditions & Branching Logic

Master program decision-making: if, elif, else, comparison operators (==, !=, >, <, >=, <=), assignment vs equality (= vs ==), chained comparisons, boolean operations (and, or, not), truth-value testing, and practical data quality threshold checks.

Read Time: 20 mins
Primary Source: Official Python 3.12+ Documentation
Interactive Labs: 8 Live Coding Workbenches
1

1. What is a Condition?

In computer programming and data analytics, a condition is an expression that evaluates to either True or False (a boolean value). Conditions allow programs to make decisions and branch their execution flow dynamically based on real data.

# Simple Real-World Example
age = 20

if age >= 18:
    print("Adult")
Program Decision Flow Model
age = 20
↓
Check Condition: age >= 18 ?
✓ TRUE
Execute indented block:
print("Adult")
✗ FALSE
Skip the indented block
Continue next lines
Key Mental Model:
Without conditions, code runs blindly from top to bottom on every single line. With conditions, your code acts intelligently—filtering anomalies, flagging critical trends, and handling distinct business edge cases.
2

2. 🔥 The IF Statement

The ifstatement is Python's fundamental branching mechanism. It has 4 structural rules:

  • if keyword initiates the conditional evaluation.
  • A condition follows (which resolves to True or False).
  • A colon (:) is strictly required at the end of the line to mark the header.
  • An indented block (standard 4 spaces) defines the code that executes if the condition is True.
Exercise 1: Write Your First IF Statement
Hands-on Lab
Task: Write an if statement that checks if age >= 18 and prints "Eligible".
3

3. 🔥 Comparison Operators

Comparison operators examine relationships between operands and return a boolean result: True or False.

OperatorMeaningExample ExpressionResult
==Equal to10 == 10True
!=Not equal to10 != 5True
>Greater than10 > 5True
<Less than10 < 5False
>=Greater than or equal to18 >= 18True
<=Less than or equal to20 <= 15False
4

4. 🔥 Predict Then Run: Comparison Sandbox

Suppose x = 10. Before running the code, predict whether each expression below will evaluate to True or False:

x > 5
x == 10
x < 3
x != 10
5

5. ⚠️ == vs = (The Most Common Beginner Bug)

Confusing assignment (=) with equality (==) is the number-one mistake made by new Python developers:

= (Assignment Operator)

Assigns a value to a variable label in memory.

age = 20
# "Store 20 inside variable age"
== (Equality Comparison)

Asks a question:"Are these two values equal?"

age == 20
# Returns: True or False
Live Bug Hunt: Fix the SyntaxError
Fix the Bug
Click Runfirst to see Python's real error message, then fix line 4:
6

6. 🔥 IF + ELSE (Two-Way Branching)

The else clause specifies an alternative suite of statements that executes when the if condition evaluates to False:

age = 16

if age >= 18:
    print("Adult")
else:
    print("Minor")  # Runs because age >= 18 is False
Exercise 2: Write an IF / ELSE Voter Checker
Coding Task
Task: If age >= 18, print "Adult"; otherwise in the else block, print "Minor".
7

7. 🔥 IF / ELIF / ELSE (Multi-Way Branching)

When evaluating scenarios with more than two possible outcomes, use elif(short for "else if"):

score = 75

if score >= 90:
    print("Grade: A")
elif score >= 75:
    print("Grade: B")  # 🎯 First match! Executes this block
elif score >= 50:
    print("Grade: C")  # Skipped, even though 75 >= 50 is also True!
else:
    print("Grade: Needs improvement")
Python Official Documentation Rule:
Python evaluates conditions in order from top to bottom. It executes the first suite whose condition is true. Once a matching branch executes, Python skips all remaining elif and else suites in the statement!
8

8. 🔥 Comparison: Multiple IF vs IF / ELIF Chain

Understanding the behavioral difference between independent if statements and an if/elif chain is critical:

❌ Multiple Independent IFs

Every single if condition is checked independently. Multiple blocks can execute!

if score >= 50:
    print("Passed")   # Runs!
if score >= 70:
    print("Honor")    # Runs ALSO!
✅ Mutually Exclusive IF / ELIF

Guarantees that only ONE branch can execute. Perfect for categorization.

if score >= 70:
    print("Honor")    # Runs, stops chain
elif score >= 50:
    print("Passed")   # Skipped!
Test Score Slider: 85
Independent IF Output:
> Pass
> Good
IF / ELIF Chain Output:
> Good
9

9. 🔥 Boolean Operators: and, or, not

Combine or invert conditions using Python's English-like logical operators:

OperatorRuleExampleResult
andTrue ONLY if both conditions are True(10 > 5) and (3 > 1)True
orTrue if at least one condition is True(10 > 5) or (1 > 10)True
notInverts the truth value (True becomes False)not (10 > 5)False
Python vs Other Languages Note:
Do not confuse Python's and and or with bitwise operators & and |. For standard conditional branching and logic decisions in Python, always use and, or, and not.
10

10. 🔥 Live Lab: Compound Conditions

Test compound conditions with live variable controls:

Age:
Has ID:
11

11. 🔥 Chained Comparisons (Pythonic Elegance)

In languages like JavaScript, C, or Java, checking if a number falls within a range requires two comparisons joined by an operator: age >= 18 && age <= 60.

Python supports mathematical chained comparisons:

age = 25

# Clean, readable mathematical notation:
if 18 <= age <= 60:
    print("Working age population")
Test 18 <= age <= 60 with different test values:
12

12. 🔥 Truth Value Testing (Truthiness vs Falsiness)

In Python, conditions are not restricted to explicit comparisons. Any Python object can be evaluated in a boolean context (such as an if condition):

❌ Built-in Falsy Values
  • False and None
  • Numeric zeros: 0, 0.0
  • Empty strings: ""
  • Empty collections: [], (),
✅ Built-in Truthy Values
  • Any non-zero number (1, -5, 0.01)
  • Any non-empty string ("Hello", "0", " ")
  • Any non-empty collection ([0], [None])
  • True
Interactive Truthiness Inspector:
13

13. 🔥 Practical Data Analytics Connection

In professional data analytics, conditional branching is the foundation of automated business logic:

1. Record Flagging

Mark transactions as high-risk, VIP, or fraud suspects based on threshold triggers.

2. Customer Binning

Categorize users into tiers (Platinum, Gold, Silver) based on annual spend volume.

3. Data Quality Guards

Filter out dirty or corrupt records (e.g. negative salaries, null emails) before modeling.

# Sales Target Performance Threshold
sales = 75000
target = 50000

if sales >= target:
    print("Target achieved: Bonus qualified")
else:
    print("Target not achieved: Review pipeline")
14

14. 🔥 Practical Scenario: Data Quality Validation Check

Before loading records into an analytics database or generating reports, analysts run data quality rules to catch corrupt rows:

Exercise: Data Ingestion Quality Rule
Analytics Scenario
Requirement: Check that 0 <= age <= 120 and salary > 0. If both pass, print "Record valid"; otherwise print "Data quality issue".
15

15. 🔥 Nested Conditions & Refactoring

An if statement can exist inside another if statement. This is called nesting:

# 1. Nested if Approach
if age >= 18:
    if has_id:
        print("Allowed")
# 2. Flattened with 'and' (Preferred)
if age >= 18 and has_id:
    print("Allowed")
Readability Principle (PEP 20 - Zen of Python):
"Flat is better than nested." When two conditions must both be true, combining them with and is generally cleaner than nesting. Use nesting only when the outer condition guards expensive operations or requires separate else handling.
16

16. 🔥 Operator Precedence in Conditions

Python evaluates expressions according to strict operator precedence rules:

  1. Parentheses () (highest precedence — evaluated first)
  2. Arithmetic operators (+, -, *, /)
  3. Comparison operators (==, !=, <, >, <=, >=)
  4. Logical not
  5. Logical and
  6. Logical or (lowest precedence)
Professional Best Practice:
Even though Python knows precedence, write (age >= 18) and has_id using parentheses for complex expressions. It eliminates ambiguity for team members and prevents subtle bugs.
17

17. 🔥 Debugging Exercise: Missing Syntax Elements

Examine the buggy code below. Click Run to see the exact error Python raises, then fix it:

18

18. 🔥 Final Live Project: Student Result Checker

Build a complete analytical classification program using all the conditional skills you've learned.

📋 Business Rules:
  • Rule 1: If attendance < 75, student is ineligible! Print: "Ineligible due to low attendance"
  • Rule 2: If eligible (attendance >= 75), evaluate academic marks:
    • Marks 75 or higher (marks >= 75) → print "Distinction"
    • Marks 40 to 74 (marks >= 40) → print "Pass"
    • Marks below 40 → print "Fail"
Final Capstone: Student Result Checker
Capstone Project
19

19. 🔥 Scenario Operator Matcher

Choose which operator structure you would use for each real-world scenario before writing the code:

1. User must be at least 18 years old.
2. Login requires BOTH a valid password AND an active 2FA token.
3. A customer qualifies for a discount if they are a student OR a senior.
4. Check if a test score is between 50 and 80 inclusive.
5. Verify that an account is NOT flagged as suspended.
20

20. Common Beginner Mistakes Checklist

MistakeIncorrect CodeCorrect CodeWhy It Fails
Using = instead of ==if age = 18:if age == 18:= assigns; raises SyntaxError in Python conditions.
Forgetting the colon :if score > 50if score > 50:Colons are mandatory in Python to introduce code blocks.
Inconsistent indentationMix of 2 and 4 spacesConsistent 4 spacesPython relies on indentation whitespace for block scoping.
Independent ifs instead of elifMultiple ifsif / elif / elseIndependent ifs can all execute; elif guarantees single selection.
Assuming "0" is falsyif "0": ...if int("0"): ...Any non-empty string is truthy in Python, even "0" or "False"!
21

21. Core Concept Quick Reference

What does if do?
Executes an indented code block only if its condition evaluates to True.
What is elif?
Checks an alternative condition only if all preceding if/elif conditions were False.
What does else do?
Default fallback block that runs when no previous conditions matched.
How does and work?
Returns True only when both expressions evaluate to truthy.
How does or work?
Returns True if at least one expression evaluates to truthy.
What is a chained comparison?
Concise syntax like 18 <= age <= 60, equivalent to a conjunction.
What is falsy in Python?
None, False, numeric 0, 0.0, empty strings "", and empty collections [].
Why do conditions matter in Data?
Filtering rows, flagging fraud, checking thresholds, and data cleaning.
22

22. Comprehensive Knowledge Assessment

Test your mastery of Python conditions, comparison operators, and logical branching:

TEST YOUR KNOWLEDGE

Python Conditions Mastery Quiz

Test your conceptual understanding of Python branching, truthiness, chained comparisons, and operator precedence.

Question 1 of 5Current Score: 0 / 0
Q1

1. What is the fundamental difference between "=" and "==" in Python?