Topics

Relational and Logical Operators

Welcome to another tutorial titled Relation and Logic. They are the fundamental bricks of a program that defines its functionality. These fundamentals decide the flow of execution and the conditions that are required to maintain that flow.

The Python language amongst other languages manages the flow of all programs, conditions are needed, so to define these conditions, relational and logical operators are needed. This is quite similar to class mathematics assignments because when you provide the compiler with some condition based on an expression, it computes the expression and executes the condition based on the output of the expression. But, for relational and logical expressions, the answers will either be True or False.

What are Operators? They are conventional symbols that bring one, two, or more operands together to form an expression. In any program, the operator and operands are two key deciding factors of the output.

In the next section, we will discuss some of the operators available in python language.

 

Python Relational Operator

In Python, the Relational operators are typically used to establish a relationship between any two operands. E.g. when you have the less than, greater than, or equal to operators. The Python programming language can understand these operators and returns the output as True or False. Check out the example below:

>>> 5 < 9

Output:

True

Since 5 is less than 9, thus the output returned is True.

 

Below are the lists of some operators:

  • Less than: It is used with <
  • Greater than: It is used with >
  • Equal to: It is used with ==
  • Not equal to: It is used with !=
  • Less than or equal to It is used with <=
  • Greater than or equal to It used with >=

 

Check out the example below:

>>> "abc" > "aaa"
>>> "abc" == "bcd"

Output:

True
False

 

Python Logical Operators

In Python, Logical operators are used in logical expressions where the operands can either be True or False. We have three basic types of logical operators:

  • Logical AND: The AND operator returns True if and only if both operands are True, and the keyword used is AND.
  • Logical OR: The OR operator returns True if either of the operands is True, and the keyword used is OR.
  • Logical NOT: The NOT operator returns True if the operand is False, and the keyword used is NOT.

Let's see a few examples:

>>> True and False

Output:

False

 

In addition, the relational expressions return a Boolean value as their output, and we can as well combine relational and logical expressions to create a meaningful expression. Check out the example below:

>>> (2 < 3) and (2 < 5)

Output:

True
>>> (2 < 3) and (2 < 1)

Output:

False

Now, let’s consider a more realistic program. Check out the example below:

>>> x = int(input())

Output:

25

 

>>> (x > 0) or (x < 100)

Output:

True