Comparison Operators
Introduction:
- Comparison operators in Python are used to compare two values and return a Boolean result (
TrueorFalse).
Python Program:
Below is a Python program that takes two numbers,
aandb, and performs comparison operations on them.pythona = 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:
- Equal (
==):- Checks if two values are equal.
- Example:
x == y
- Not Equal (
!=):- Checks if two values are not equal.
- Example:
x != y
- Greater Than (
>):- Checks if the value on the left is greater than the value on the right.
- Example:
x > y
- Less Than (
<):- Checks if the value on the left is less than the value on the right.
- Example:
x < y
- 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
- 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:
- 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))
- 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!