Categories: python

Relational & Logical Operators in Python

In Python, operators are specialized symbols that perform different computations. To create an expression, we combine operators and operands. Expressions are merely values’ representations. The fundamental building blocks of a program that define its functionality are relation and logic.

Relational operator:

Value comparisons are done using relational operators, also known as comparison operators. It responds to the condition by returning either True or False.

OperatorDescriptionSyntax
>Greater than: True if the left operand is greater than the rightx > y
<Less than: True if the left operand is less than the rightx < y
==Equal to: True if both operands are equalx == y
!=Not equal to – True if operands are not equalx != y
>=Greater than or equal to True if the left operand is greater than or equal to the rightx >= y
<=Less than or equal to True if the left operand is less than or equal to the rightx <= y
Example:
a = 9
b = 5

print(a < b)
print(a > b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Output:
False
True
False
True
True
False
Logical Operators:

To decide on an expression, logical operators are mainly used. The following logical operators are supported by Python.

OperatorDescriptionExample
andIf both expressions are true, then the condition will be true. If a and b are the two expressionsa → true, b → true
then a and b → true.
orIf one of the expressions is true, then the condition will be true. If a and b are the two expressions,a → true, b → false => a or b → true.
notIf an expression a is true, then not (a) will be false and vice versa.a → true=> not a → false.
Example:
a = 5

print(2 < 3) and (2 < 5)
print(2 < 3) or (2 < 5)
print(not a)
Output:
True
True
False

Note: also read about Python Tuple

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

13 hours ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

3 days ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

3 weeks ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

1 month ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

1 month ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

2 months ago