×

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 tuple() function

Python tuple() function The tuple() function in Python creates a tuple object. Syntax tuple([iterable]) Parameter Iterable: This parameter represents a sequence, collection or an iterator object. Return This function returns a tuple object. Example 1 # Python Program explaining #...

1 minute read.

How to Print Pattern in Python

How to Print Pattern in Python. Pattern programs are really important for beginners and they are always asked in all the technical interviews. Multiple loops approach is used to print the different...

6 minutes read.

Conditional Expressions in Python

In Python conditional expression are sometimes referred to operator called as ternary operator. Not only Python supports ternary operator but many other programming languages supports it. Ternary operator are the...

2 minutes read.

Python Multithreading

In python, we can implement multithreading. In this tutorial, we will understand the basics of implementing multithreading in a python programming language. Multithreading is just like multiprocessing. We use it...

4 minutes read.

Speech Recognition Module in Python

Speech Module in Python: Converting text to speech, known as Speech Synthesis, this process is the computer-generated recreation of human speech. This module converts the human language text into human-like...

8 minutes read.

Python Built-in Functions

Python Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. The Python built- in functions are as follow: Methods Explaining abs() The abs() function returns...

6 minutes read.

Python Control Statements

Control statements are under the roof topic of loops and loops in python are defined as iteratively and repeatedly working on source code. Loop control statements are defined as they...

3 minutes read.

XXhash Python Examples

XXhash Python: xxHash is an extremely rapid hash calculation that operates inside the confines of RAM. Code is incredibly convenient, and hashes (almost nothing/large endian) are same at all levels. Execution of...

4 minutes read.

Python Knapsack problem

Python Knapsack problem Before we dig down about Knapsack problems in Python, first let's have a look at what is actually a knapsack problem. What is a knapsack problem? A problem from the...

5 minutes read.

Python Program to Print Sum of all Elements in an Array

Python program to print sum of all elements in an array A set of objects stored in contiguous memory locations is referred to as an array. The concept is to keep...

2 minutes read.

Subprocess Module in Python

What is a Process? Every program will have its respective system state, i.e., the state in which it is running. A program that is in a running state or in a...

7 minutes read.

Nested for Loop in Python

"Loop" is one of the foundation concepts to learn programming in any language. Nested loops are significant steps in solving many types of problems, ranging from basic to complex scenarios....

9 minutes read.

Exclusive OR in Python

In Python, the exclusive OR (XOR) operator is represented by the caret symbol (^). It compares each bit of the first operand to the corresponding bit of the second operand,...

3 minutes read.

GUI Calendar using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

3 minutes read.

Python List sort() method

The list.sort () method in Python sorts the items of the list in place. Syntax list.sort(key=None, reverse=False) Parameter reverse: If a Boolean value ‘True’ is passed, the  sorting will be done in the descending order else for ‘False’...

2 minutes read.

Number pattern in Python

Number pattern in Python: This article explains how to print number patterns in Python. The FOR loop, while loop, and range() functions are used in the following Python programs to...

4 minutes read.

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason,...

17 minutes read.

Python MongoDB Tutorial

An Introduction to MongoDB MongoDB is a document-oriented database application. It is an Open-source and platform-independent program. MongoDB is similar to few NoSQL databases that store the data in the documents...

17 minutes read.

Best Way to Learn Python for Free

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. Learning Python is a step towards coding. Python gets...

5 minutes read.

How to print in same line in python

How to Print in the Same Line in Python To print in Python, we use the print () function and the syntax of print () goes like this: print (values, sep =...

3 minutes read.