Comparison Operators

Introduction:

  • Comparison operators in Python are used to compare two values and return a Boolean result (True or False).

Python Program:

  • Below is a Python program that takes two numbers, a and b, and performs comparison operations on them.

    python
    a = 5
    b = 2
    
    print('a == b :', (a == b))  # Comparison Equal to
    print('a != b :', (a != b))  # Comparison Not Equal to
    print('a > b  :', (a > b))   # Comparison Greater than
    print('a < b  :', (a < b))   # Comparison Less than
    print('a >= b :', (a >= b))  # Comparison Greater than or Equal to
    print('a <= b :', (a <= b))  # Comparison Less than or Equal to
    

Output:

a == b : False
a != b : True
a > b  : True
a < b  : False
a >= b : True
a <= b : False

Detailed Tutorials:

  • Here are detailed tutorials covering each of the comparison operators with examples:
  1. Equal (==):
    • Checks if two values are equal.
    • Example: x == y
  2. Not Equal (!=):
    • Checks if two values are not equal.
    • Example: x != y
  3. Greater Than (>):
    • Checks if the value on the left is greater than the value on the right.
    • Example: x > y
  4. Less Than (<):
    • Checks if the value on the left is less than the value on the right.
    • Example: x < y
  5. Greater Than or Equal To (>=):
    • Checks if the value on the left is greater than or equal to the value on the right.
    • Example: x >= y
  6. Less Than or Equal To (<=):
    • Checks if the value on the left is less than or equal to the value on the right.
    • Example: x <= y

Exercises:

  1. Basic Comparison Operations:
    • Write a program to perform basic comparison operations (equal, not equal, greater than, less than) on two numbers entered by the user.

      python
      # Read two numbers from user
      a = int(input("Enter first number: "))
      b = int(input("Enter second number: "))
      
      # Perform comparison operations
      print('a == b :', (a == b))
      print('a != b :', (a != b))
      print('a > b  :', (a > b))
      print('a < b  :', (a < b))
      
  2. Advanced Comparison Operations:
    • Write a program to perform greater than or equal to and less than or equal to comparisons on two numbers entered by the user.

      python
      # Read two numbers from user
      a = int(input("Enter first number: "))
      b = int(input("Enter second number: "))
      
      # Perform advanced comparison operations
      print('a >= b :', (a >= b))
      print('a <= b :', (a <= b))
      

Summary:

  • Comparison operators in Python are essential for comparing values and making decisions in your programs. Practice using these operators to become proficient in writing conditional statements and comparisons in Python!