Python Encyclopedia for Academics
  • Course Outline
  • Artificial Intelligence
    • Data Science Foundation
      • Python Programming
        • Introduction and Basics
          • Variables
          • Print Function
          • Input From User
          • Data Types
          • Type Conversion
        • Operators
          • Arithmetic Operators
          • Relational Operators
          • Bitwise Operators
          • Logical Operators
          • Assignment Operators
          • Compound Operators
          • Membership Operators
          • Identity Operators
      • Numpy
        • Vectors, Matrix
        • Operations on Matrix
        • Mean, Variance, and Standard Deviation
        • Reshaping Arrays
        • Transpose and Determinant of Matrix
      • Pandas
        • Series and DataFrames
        • Slicing, Rows, and Columns
        • Operations on DataFrames
        • Different wayes to creat DataFrame
        • Read, Write Operations with CSV files
      • Matplotlib
        • Graph Basics
        • Format Strings in Plots
        • Label Parameters, Legend
        • Bar Chart, Pie Chart, Histogram, and Scatter Plot
  • Machine Learning Algorithms
    • Regression Analysis In ML
      • Regression Analysis in Machine Learning
      • Proof of Linear Regression Formulas
      • Simple Linear Regression Implementation
      • Multiple Linear Regression
      • Advertising Dataset Example
      • Bike Sharing Dataset
      • Wine Quality Dataset
      • Auto MPG Dataset
    • Classification Algorithms in ML
      • Proof of Logistic Regression
      • Simplified Mathematical Proof of SVM
      • Iris Dataset
  • Machine Learning Laboratory
    • Lab 1: Titanic Dataset
      • Predicting Survival on the Titanic with Machine Learning
    • Lab 2: Dow Jones Index Dataset
      • Dow Jones Index Predictions Using Machine Learning
    • Lab 3: Diabetes Dataset
      • Numpy
      • Pandas
      • Matplotlib
      • Simple Linear Regression
      • Simple Non-linear Regression
      • Performance Matrix
      • Preprocessing
      • Naive Bayes Classification
      • K-Nearest Neighbors (KNN) Classification
      • Decision Tree & Random Forest
      • SVM Classifier
      • Logistic Regression
      • Artificial Neural Network
      • K means Clustering
    • Lab 4: MAGIC Gamma Telescope Dataset
      • Classification in ML-MAGIC Gamma Telescope Dataset
    • Lab 5: Seoul Bike Sharing Demand Dataset
      • Regression in ML-Seoul Bike Sharing Demand Dataset
    • Lab 6: Medical Cost Personal Datasets
      • Predict Insurance Costs with Linear Regression in Python
    • Lab 6: Predict The S&P 500 Index With Machine Learning And Python
      • Predict The S&P 500 Index With Machine Learning And Python
  • Artificial Neural Networks
    • Biological Inspiration vs. Artificial Neurons
    • Review linear algebra and calculus essentials for ANNs
    • Activation Function
  • Mathematics
    • Pre-Calculus
      • Factorials
      • Roots of Polynomials
      • Complex Numbers
      • Polar Coordinates
      • Graph of a Function
    • Calculus 1
      • Limit of a Function
      • Derivative of Function
      • Critical Points
      • Indefinite Integrals
  • Calculus 2
    • 3D Coordinates and Vectors
    • Vectors and Vector Operations
    • Lines and Planes in Space (3D)
    • Partial Derivatives
    • Optimization Problems (Maxima/Minima) in Multivariable Functions
    • Gradient Vectors
  • Engineering Mathematics
    • Laplace Transform
  • Electrical & electronics Eng
    • Resistor
      • Series Resistors
      • Parallel Resistors
    • Nodal Analysis
      • Example 1
      • Example 2
    • Transient State
      • RC Circuit Equations in the s-Domain
      • RL Circuit Equations in the s-Domain
      • LC Circuit Equations in the s-Domain
      • Series RLC Circuit with DC Source
  • Computer Networking
    • Fundamental
      • IPv4 Addressing
      • Network Diagnostics
  • Cybersecurity
    • Classical Ciphers
      • Caesar Cipher
      • Affine Cipher
      • Atbash Cipher
      • Vigenère Cipher
      • Gronsfeld Cipher
      • Alberti Cipher
      • Hill Cipher
Powered by GitBook
On this page
  • What are Logical Operators?
  • The Three Logical Operators
  • Step 1: Basic Setup and Introduction
  • Step 2: Using and
  • Step 3: Using or
  • Step 4: Using not
  • Step 5: Combine Logical Operators
  • Common Use Cases in Machine Learning:
  • Step-by-Step Mini Project (Example)
  • Summary
  • Keywords
  1. Artificial Intelligence
  2. Data Science Foundation
  3. Python Programming
  4. Operators

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

Operator
Description
Example

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

a = True
b = False

Step 2: Using and

Explanation:

and returns True only if both sides are True.

print(a and b)  # False, because b is False
print(True and True)  # True
print(False and True)  # False

Practical Machine Learning Use Case:

Suppose you're checking if a data point is in range and labeled as valid:

feature_value = 0.75
is_labeled = True

if feature_value > 0.5 and is_labeled:
    print("Use this data point")
else:
    print("Ignore this data point")

Step 3: Using or

Explanation:

or returns True if at least one side is True.

print(a or b)  # True, because a is True
print(False or False)  # False

ML Example – Feature Checks:

is_missing = False
is_corrupted = True

if is_missing or is_corrupted:
    print("Drop this sample")
else:
    print("Keep it")

Step 4: Using not

Explanation:

not inverts the boolean value.

print(not a)  # False, because a is True
print(not b)  # True, because b is False

ML Example – Filtering Data:

is_outlier = False

if not is_outlier:
    print("Include in training")
else:
    print("Exclude from training")

Step 5: Combine Logical Operators

You can mix and, or, and not in one condition.

accuracy = 0.91
precision = 0.88
is_outlier = False

if accuracy > 0.90 and (precision > 0.85 or not is_outlier):
    print("Model is acceptable")
else:
    print("Needs improvement")

Truth Table (Great for Intuition)

A
B
A and B
A or B
not A

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:

Situation
Example

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:

data = [
    {"name": "Alice", "age": 25, "score": 88, "valid": True},
    {"name": "Bob", "age": 17, "score": 75, "valid": False},
    {"name": "Carol", "age": 30, "score": 95, "valid": True}
]

for row in data:
    if row["age"] > 18 and row["valid"]:
        print(f"{row['name']} is eligible for training.")

Summary

Operator
Usage
When to Use

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

PreviousBitwise OperatorsNextAssignment Operators

Last updated 2 months ago