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
  • Step 1: What Are Relational Operators?
  • Step 2: List of Relational Operators in Python
  • Step 3: Try Simple Examples
  • Step 4: Use in Real-world Examples
  • Step 5: Practical Use in Machine Learning
  • Step 6: Combine with Logical Operators
  • Step 7: Use with NumPy Arrays (Very Important for ML)
  • Summary Table in Code
  • Keywords
  1. Artificial Intelligence
  2. Data Science Foundation
  3. Python Programming
  4. Operators

Relational Operators

Nerd Cafe

Step 1: What Are Relational Operators?

Relational operators (also known as comparison operators) are used to compare two values. The result of a comparison is always a Boolean:

  • True or

  • False

Step 2: List of Relational Operators in Python

Operator
Description
Example

==

Equal to

a == b

!=

Not equal to

a != b

>

Greater than

a > b

<

Less than

a < b

>=

Greater than or equal to

a >= b

<=

Less than or equal to

a <= b

Step 3: Try Simple Examples

a = 10
b = 20

print(a == b)  # False
print(a != b)  # True
print(a > b)   # False
print(a < b)   # True
print(a >= b)  # False
print(a <= b)  # True

Note: Always remember that relational operations return True or False.

Step 4: Use in Real-world Examples

Example 1: Age Check System

age = 25
if age >= 18:
    print("You're eligible to vote.")
else:
    print("Sorry, you're underage.")

Output: "You're eligible to vote."

Example 2: Comparing Strings (Alphabetical Order)

print("apple" < "banana")  # True
print("cat" > "bat")       # True

Note: String comparison is based on Unicode (ASCII) order, not dictionary order.

Step 5: Practical Use in Machine Learning

Relational operators are heavily used in ML tasks such as:

  • Filtering datasets

  • Conditional logic

  • Feature selection

  • Performance evaluation

Example 3: Thresholding Predictions

Suppose you’re doing binary classification, and you want to classify predictions above 0.5 as class 1:

prediction = 0.72

if prediction >= 0.5:
    print("Class 1")
else:
    print("Class 0")

Output: Class 1

Example 4: Filtering with Pandas (ML-related)

import pandas as pd

# Sample data
data = {
    'Name': ['Anna', 'Bob', 'Charlie'],
    'Score': [85, 42, 73]
}

df = pd.DataFrame(data)

# Get only rows with Score >= 70
passed = df[df['Score'] >= 70]
print(passed)

Output:

     Name  Score
0    Anna     85
2  Charlie     73

Note: Relational operators work element-wise in Pandas.

Step 6: Combine with Logical Operators

x = 80

if x > 70 and x < 90:
    print("Good score")

Output: "Good score"

This is common in machine learning when checking conditions like:

if accuracy >= 0.8 and loss < 0.4:
    print("Model is acceptable.")

Step 7: Use with NumPy Arrays (Very Important for ML)

import numpy as np

arr = np.array([0.3, 0.7, 0.1, 0.8])

# Thresholding: Get boolean array
mask = arr > 0.5
print(mask)  # [False  True False  True]

# Apply mask
print(arr[mask])  # [0.7 0.8]

Use case: This is used for filtering predictions, feature values, and more.

Summary Table in Code

x = 5
y = 10

print("x == y:", x == y)
print("x != y:", x != y)
print("x > y:", x > y)
print("x < y:", x < y)
print("x >= y:", x >= y)
print("x <= y:", x <= y)

Keywords

Relational operators, Python comparison, Python boolean, equality operator, greater than, less than, Python >=, Python <=, Python !=, boolean logic, machine learning conditions, pandas filtering, numpy comparison, thresholding predictions, conditional logic, Python operators, Python data science, binary classification, data filtering, logical comparisons, ned cafe

PreviousArithmetic OperatorsNextBitwise Operators

Last updated 2 months ago