Relational and logical operators in Python

Relational operators are used to compare values with each other. They return a logical result: true or false. Values that are linked with relational operators are called elementary statements in propositional logic.
A typical example of a Boolean logical operator is the and operation: It always returns true if all operands are also true.

OperatorDescription
<smaller
>greater
==equal
!=unequal
<=less than or equal to
>=greater than or equal to
notexpression is false
andboth expressions are true
orat least one expression is true

Code Example

a, b, i = 0, 4, 10
while a != b and i >= a + b:
    print(str(a)+ " is unequal " + str(b))
    a = a + 1

print(str(a) + " is equal " + str(b))
Code Explanation

This code uses a while loop to execute a block of code multiple times as long as the condition in the while statement is True. The condition in this code is a != b and i >= a + b. The loop will run as long as a is not equal to b and i is greater than or equal to a + b.

The code starts by initializing the variables a, b, and i to 0, 4, and 10, respectively. Within the loop, the value of a is incremented by 1 in each iteration, and the current value of a is printed if a is not equal to b. This continues until either a becomes equal to b or i becomes less than a + b.

At the end of the loop, the code prints a is equal b. If the loop terminated because a became equal to b, then this statement will be printed.

Output
0 is unequal 4
1 is unequal 4
2 is unequal 4
3 is unequal 4
4 is equal 4