×

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 program to display ASCII value of the character

Python program to display ASCII value of the character The full form of ASCII is American Standard Code for Information Interchange. This example explains a program in Python to find the...

1 minute read.

Python Slice from Last Occurrence of K

Introduction We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on...

3 minutes read.

How to Sort a String in Python?

The characters in the string are sorted or put in alphabetical order using the sort string function in Python. Python has built-in techniques for sorting strings available. Since we occasionally...

6 minutes read.

Python Tutorial

Python tutorial is a widely used programming language which helps beginners and professionals to understand the basics of Python programming easily. Python is a high-level, easy, interpreted, general-purpose, and dynamic programming...

19 minutes read.

Python Set add() Method

Python Set add() Method The set.add() method adds the specified element to a set. If the element is already present in the set, it doesn't add it. Syntax set.add(element) Parameter element- This parameter represents the element that...

1 minute read.

Python String ljust() method

Python String ljust() method The string.ljust() method in Python will left align the string, where the padding is done using the parameter fillchar (space is default). Syntax String.ljust(width[, fillchar]) Parameter width: This parameter represents the...

2 minutes read.

Find key from value in dictionary python

Python: Python programming language is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a...

5 minutes read.

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.

Python max() function

Python max() function The max() function in Python returns the largest item in an iterable or the largest of two or more arguments. Syntax max(iterable, *[, key, default])               or max(arg1, arg2, *args[, key])   Parameter arg1, arg2, *args: This...

1 minute read.

Python Call Function

In this article, you will learn about calling a function in Python. But before learning this, we should know about functions in Python.So, let’s get some overview of functions in...

6 minutes read.

Python String encode() method

Python String encode() method The string.encode() method in Python returns an encoded version of the string. The default encoding is the current default string encoding Syntax String.encode([encoding[,errors]]) Parameter Encoding: This parameter represents a String specifying...

2 minutes read.

Python System Command

To execute a program in Python, we need to execute some shell commands to run our program on the computer. Python will provide some shell commands in our background to...

3 minutes read.

Python String isspace() method

Python String isspace() method The string.isspace() method returns a Boolean value true if there are only whitespace characters in the given string. This function is used to check if the given...

2 minutes read.

Python pycountry

What is Pycountry? Python programming language: 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...

4 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

How to create a list in Python?

How to create a list in python Python is known for its versatility and its data structures help us to perform different kinds of operations on various datasets irrespective of their...

4 minutes read.

How to Install Pandas in Python?

Pandas is a library created in Python for handling and analyzing data. Pandas provides a variety of procedures and data structures for manipulating time series and numerical data.  Pandas is...

3 minutes read.

SKLearn Clustering

These are ml methods thatare responsible for detecting patterns and the similarities within the data.The clustering methods are unsupervised.Here the data is clustered to form groups with the help of...

3 minutes read.

Operator Overloading in Python

In any programming language, + is an arithmetic operator; it adds two numbers to give the sum. Have you ever tried to concatenate two strings? Concatenating two strings is adding...

5 minutes read.

What is online python free IDE

An IDE is an acronym that stands for “Integrated development environment.” It is a software environment that has a software development package that consists of the code editor and builds...

4 minutes read.