Logical Operators
Nerd Cafe
What are Logical Operators?
Logical operators are used to combine conditional statements (Boolean expressions). They help us make decisions in our code.
The Three Logical Operators
and
True if both are True
A and B
or
True if at least one is True
A or B
not
True if condition is False
not A
Step 1: Basic Setup and Introduction
Step 2: Using and
and
Explanation:
and
returns True
only if both sides are True
.
Practical Machine Learning Use Case:
Suppose you're checking if a data point is in range and labeled as valid:
Step 3: Using or
or
Explanation:
or
returns True
if at least one side is True
.
ML Example – Feature Checks:
Step 4: Using not
not
Explanation:
not
inverts the boolean value.
ML Example – Filtering Data:
Step 5: Combine Logical Operators
You can mix and
, or
, and not
in one condition.
Truth Table (Great for Intuition)
True
True
True
True
False
True
False
False
True
False
False
True
False
True
True
False
False
False
False
True
Common Use Cases in Machine Learning:
Data validation
if age > 18 and income > 30000:
Missing/Invalid values
if missing or corrupted:
Feature combinations
if (x1 > 0.5 and x2 < 1.2):
Filter training data
if not is_outlier:
Hyperparameter logic
if lr < 0.01 and batch_size > 32:
Step-by-Step Mini Project (Example)
Let’s use logical operators to filter valid rows in a dataset:
Summary
and
Both must be True
Data must meet multiple strict conditions
or
At least one is True
One of several conditions is enough
not
Reverses condition
Filter out a certain group
Keywords
logical operators
, python
, and operator
, or operator
, not operator
, boolean logic
, conditional statements
, data filtering
, machine learning
, feature validation
, truth table
, data preprocessing
, boolean expressions
, data quality check
, logical conditions
, model evaluation
, data selection
, outlier filtering
, code examples
, python logic
, nerd cafe
Last updated