×

Python Logical Operators

In python, there are many operators which we use in our program. Operators are used in manipulating a particular value or operand. Logical operators are used mainly to evaluate an expression that makes the decision.

Operators

Operators play an important role in many programming languages like C, Python, C++, etc. Operators are mainly used for performing operations on variables and values.

Operators are special symbols that perform logical, mathematical, relational, and arithmetic computations to get the final result. In other words, operators in python are used to perform operations between variables.

Example:  Consider an equation 5+6=11. From the example, the operators are + and =; these operators perform operations like addition, subtraction, multiplication, etc.

Python Logical Operators

There are two operands from the above flowchart, namely operand 1 and operand 2; when we add an operator between them, we can get the result according to the type of operator we are using here.

Operands

Operands are nothing but variables on which operations are done. 

Example: Consider an equation c + d – e = f, here c, d, e, f are operands and +, -, = are operators.

Python has different operators. They are:

  1. Arithmetic operators
  2. Assignment operators
  3. Comparison operators
  4. Logical operators
  5. Identity operators
  6. Bitwise operators
  7. Membership operators

Here we are discussing logical python operators.

Logical Operators

 To combine conditional statements, we use logical operators. We use logical operators to check multiple conditions at the same time. Python supports three logical operators, they are:

  1. And
  2. Or
  3. Not

Logical And Operator

The “LOGICAL AND OPERATOR" checks whether the given condition is TRUE. It checks the given conditions simultaneously.

Example: consider two operands, 'a' and 'b'. This shows that the AND OPERATOR will return TRUE only if both conditions are TRUE, and it returns FALSE only if any of the conditions is FALSE.

Let us take an example program that uses AND OPERATOR to check whether the conditions are TRUE or FALSE.

EXAMPLE PROGRAM

              Book cost = 200

              Book cost > 100 and Book cost < 300

This is the way to write AND condition between statements or conditions.

The above example program shows how "OR OPERATOR" works.

Output

Python Logical Operators

Here Book cost>100 and the Book cost<300 returns TRUE because both the conditions return   TRUE. From the given condition Book cost =200, both conditions check this statement and return the final result.

x                     y                x and y
                True                 True                  True
                True                 False                  False
                False                 True                  False
                False                 False                  False

From the above table, we understand that if both x and y are TRUE, then x and y return TRUE. If any of the conditions of both x and y are false, then it returns FALSE.

Logical Or Operator

As discussed, AND OPERATOR, the “OR OPERATOR” also check multiple conditions simultaneously. Still, there is a small change: the OR OPERATOR returns true if the individual condition or both conditions are True. This is the way to write the "OR" condition between statements.

EXAMPLE PROGRAM

Book cost=300

Book cost > 400 or Book cost < 200

The above example shows us how to use “OR OPERATOR”.

Output

Python Logical Operators

From the above example, the Book cost >400 and the Book cost<200 return FALSE because both conditions evaluate FALSE. Both conditions check the given condition: Book cost=300 and returns result.

               x                y             x or y
            True            True              True
            True            False              True
            False            True              True
            False             False              False

From the above table, if both x and y are TRUE, then it returns TRUE; if the individual condition is TRUE, it returns TRUE. It will return FALSE when both statements need to be FALSE.

Logical Not Operator

This operator is another type of logical operator. This LOGICAL NOT OPERATOR only applies to one condition and will reverse the given condition.

 It works with a single Boolean value. If the Boolean value is TRUE, then this operator returns FALSE.

From this, we understood that if the condition is TRUE, it returns FALSE, and if the condition is FALSE, then it returns TRUE.

EXAMPLE PROGRAM

Book cost =300

not Book cost > 500

This is the way to write LOGICAL NOT OPERATOR for a given condition.

The below example shows us how to write NOT OPERATOR.

Output  

Python Logical Operators

From the above example, we observe that when Book cost = 300 and it returns TRUE when NOT OPERATOR was involved. Indeed, the Book cost is not greater than 500, so it returns TRUE.     

                        x                      Not x
                    True                      False
                    False                      True

From the above table, we observe that if the condition is TRUE, then not x becomes FALSE, and if the condition is FALSE, then not x becomes TRUE.

Rather, we can also use the combination of AND and NOT OPERATORS simultaneously.

Here is the example program

Program with Output

Python Logical Operators

From the above example, we noticed that the output is FALSE because we combined NOT AND OPERATORS. From this example, we observed that Book cost = 500, and the conditions Book cost > 300 and Book cost < 600 are TRUE. The result becomes FALSE when we apply NOT OPERATOR because it returns the reverse of the given condition.

Precedence of Logical Operators in Python

In python, an expression combines operands, operators, and function calls. Python interpreter can evaluate a valid expression.

The word precedence shows how to follow the order of operations if there are many operators. It mainly tells the order of operators and which operations need to perform first.

In many cases, one expression can contain two or more operators. At that time, the operator precedence takes place.

Python Logical Operators

The above figure shows that NOT OPERATOR has the highest precedence. The AND OPERATOR has the second precedence, and OR OPERATOR has the lowest precedence.

EXAMPLE PROGRAM

#Precedence of ‘OR’ and ‘AND’ OPERATORS
name= “ABC”
age= 16


if (name == “ABC” or name ==” XYZ”) and age<=17:
Print (“Your name is correct”)


else:
      Print (“Your name is incorrect”)

Output

Your name is correct.

In the above example, the precedence of AND operator is higher than the precedence of the OR operator. So first, it checks the precedence, then returns the desired output rather than checking the if and else block.

Associativity for Python Operators

Associativity in python maintains the order for an expression when multiple operators have the same operator precedence, as we know that operators have associativity from left to right.

For suppose, associativity will let you know the order of operations if two operators have the same precedence.

Let us consider multiplication and floor division which have the same precedence. It should be evaluated from left to right if it occurs in an expression. That is left operator will be evaluated first.

EXAMPLE PROGRAM

#This program shows the left-right associativity of operators


Print (  7 * 8 // 4)

Output

14

Here OR and FLOOR DIVISION have the same precedence, so OR is evaluated first because associativity checks from left to right.

# This program shows the left-right associativity of operators
Print ( 8 // 4*2)

Output

4

Here OR and FLOOR DIVISION have the same precedence, so FLOOR DIVISION is evaluated first because associativity checks from left to right.

Applications of Operators

  1. These are used for manipulating each data item and returning a result.
  2. Operators are represented using keywords and special characters.
  3. Operations on operands and operators will give the result.
  4. It also shows the precedence of operators, like which operator should be evaluated first.

Related Topics

Python Logical Operators

In python, there are many operators which we use in our program. Operators are used in manipulating a particular value or operand. Logical operators are used mainly to evaluate an...

7 minutes read.

How to Reverse a number in Python?

In Python, conditional statements can be combined with the list() method, slice() method, recursion() method, and other predefined techniques to generate reverse logical functions. The reverse() method is the most...

7 minutes read.

Python lambda() Function

In this tutorial, we will learn about a new concept known as the Lambda function. It is a relatively new concept while learning Python. Python lambda functions are anonymous functions. It...

3 minutes read.

Python String lower() method

Python String lower() method The string.lower() method in Python returns a string where all characters are lower case. Syntax string.lower() Parameter NA Return This method returns a string where all characters are lower case. Example 1 # Python...

1 minute read.

Python Write Excel File

Python Write Excel File The Python xlwt module is used to write an excel file and perform multiple operations on it. It can be used to write text, numbers, and formulas for multiple...

3 minutes read.

Count Number of Keys in Dictionary Python

Dictionary is a particular data type in python. Dictionary stores unique values by taking different keys and their assigned values. Through this article, we will learn about python dictionary count,...

3 minutes read.

How to reverse a string in python

How to reverse a string in python A Brief About Strings- The String is a data type in Python that has a sequence of characters. This series of characters are represented in...

4 minutes read.

List Comprehension in Python3

List A list in python is a complex data type, and a list is a collection of the number of data. The data variable may or may not be of the...

5 minutes read.

How to Parse JSON in Python

JSON The JSON, the Java Script Object Notation, is an open standard file designed for data interchange; it is light-weighted text. The JSON uses human-readable text to store and transmit the...

4 minutes read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python complex() class

Python complex() class The complex() class in Python returns a complex number or converts a string or number to a complex number. Syntax class complex([real[, imag]]) Parameter Real: This parameter consists of a number representing the real...

1 minute read.

Python Parser

Introduction : Parsing is referred to as the processing and translation of a Python program into machine language. In general, we could indeed say that the command parse is used to...

4 minutes read.

Python list() | List class in Python

The list() class in Python creates a list object where the list object is a collection which is ordered and changeable. Syntax class list([iterable]) Parameter Iterable: It is a required parameter which represents a sequence, collection...

1 minute read.

Google Python Class

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Python Command line Arguments

Python Command line Arguments The command-line argument is used to the change functionality of the program. It's an extra command the programmer can use while launching a program. These commands have many uses...

7 minutes read.

Reason for Python So Popular

One of the languages that is witnessing outstanding development and acceptance every year in Python. Python has emerged as the programming language with the greatest rate of growth, and Stack...

3 minutes read.

Nested List in Python

The list is an inbuilt sequential data type in Python. It is a very useful and frequently used data type. A list can store any number of data items of...

4 minutes read.

How to Convert String to List In Python?

How to Convert String to List In Python? We all are familiar with what strings and lists are, let us have a quick revision on them- Strings are a sequence of characters...

4 minutes read.

Python locals() function

Python locals() function The locals() function in Python updates and returns a dictionary representing the current local symbol table. Syntax locals() Parameter NA Return This function returns the local symbol table as a dictionary or returns free...

1 minute read.