The Wayback Machine - https://web.archive.org/web/20241009145424/https://www.geeksforgeeks.org/g-fact-29-logical-and-bitwise-not-operators-on-boolean/
Open In App

G-Fact 19 (Logical and Bitwise Not Operators on Boolean)

Last Updated : 28 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Most of the languages including C, C++, Java, and Python provide a boolean type that can be either set to False or True. In this article, we will see about logical and bitwise not operators on boolean.

Logical Not (or !) Operator in Python

In Python, the logical not operator is used to invert the truth value of a Boolean expression, returning True if the expression is False, and False if the expression is True. In the below example, we have used the logical not operator in Python. Here, the variable a is assigned the value True, and the variable b is assigned the inverse of a using the not operator. The output of the print statements shows that a is True, while b is False.

Python3




a = True
b = not a
 
print(a)  # True
print(b)  # False


Output

True
False

Time Complexity: O(1)
Space Complexity: O(1)

Consider below programs that use the Logical Not (or !) operator on a boolean.

C++




// A C++ program that uses Logical Not or ! on boolean
#include <iostream>
using namespace std;
 
int main()
{
    // we are making variable store bool expression of false
    // and true, it can be also written as (1) for 'true' and
    bool is_it_true = false;
    bool is_it_false = true;
 
    // This code below print first false (0) and then true
    cout << is_it_true << endl;
    cout << !is_it_true << endl;
 
    // This code below print first true (1) and then false
    cout << is_it_false << endl;
    cout << !is_it_false << endl;
    return 0;
}


Java




// A Java program that uses Logical Not or ! on boolean
import java.io.*;
 
class GFG {
    public static void main (String[] args) {
    
      boolean a = true, b = false;
       
      System.out.println(!a);
      System.out.println(!b);
    }
}


Python3




# A Python program that uses Logical Not or ! on boolean
a = not True
b = not False
print a
print b


C#




// C# program that uses Logical
// Not or ! on boolean
using System;
 
class GFG
{
    public static void Main ()
    {
        bool a = true, b = false;
        Console.WriteLine(!a);
        Console.WriteLine(!b);
    }
}


Javascript




<script>
// A javascript program that uses Logical Not or ! on boolean
     
        var a = true, b = false;
        document.write(!a+"<br/>");
        document.write(!b);
 
// Output: False
// True
 
// This code contributed by gauravrajput1
</script>


Output

0
1
1
0

Time complexity: O(1)
Auxiliary space: O(1) 

Bitwise Not (or ~) Operator in Python

The bitwise not operator is used to invert the bits of an integer, including its sign bit, which changes the sign of the integer. In this example, we are using Btiwise Not ( or ~) operator. Code implementation is given below.

C++




#include <iostream>
 
using namespace std;
 
int main()
{
    bool a = true, b = false;
    cout << ~a << endl;
    cout << ~b << endl;
 
    return 0;
}


Java




// A Java program that uses Bitwise Not or ~ on boolean
import java.io.*;
 
class GFG
{
    public static void main (String[] args)
    {
  int a = 1, b = 0;
        System.out.println(~a);
        System.out.println(~b);
    }
}


Python




# A Python program that uses Bitwise Not or ~ on boolean
a = True
b = False
print ~a
print ~b


C#




using System;
 
class Program
{
    static void Main(string[] args)
    {
        bool a = true, b = false;
        Console.WriteLine(~Convert.ToInt32(a));
        Console.WriteLine(~Convert.ToInt32(b));
    }
}


Javascript




// A JavaScript program that uses Bitwise Not or ~ on boolean
        var a = true, b = false;
        console.log(~a);
        console.log(~b);
 
// This code is contributed by aaprilq6i.


Output

-2
-1

In this example, the variable a is assigned the value 5, and the variable b is assigned the inverse of a using the bitwise not operator. The output of the print statements shows that a is 5, while b is -6.

Python




a = 5
b = ~a
 
print(a)  # 5
print(b)  # -6


Output

5
-6

Note that the bitwise not operator only works on integers, and not on Boolean values. Also, the bitwise not operator is different from the logical not operator, and should be used with caution.

Conclusion

“Logical not or !” is meant for boolean values and “bitwise not or ~” is for integers. Languages like C/C++ and python do auto promotion of boolean to integer type when an integer operator is applied. But Java doesn’t do it.



Similar Reads

Boolean Operators - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variable
5 min read
Python 3 - Logical Operators
Logical Operators are used to perform certain logical operations on values and variables. These are the special reserved keywords that carry out some logical computations. The value the operator operates on is known as Operand. In Python, they are used on conditional statements (either True or False), and as a result, they return boolean only (True
4 min read
Python Logical Operators
Python logical operators are used to combine conditional statements, allowing you to perform operations based on multiple conditions. These Python operators, alongside arithmetic operators, are special symbols used to carry out computations on values and variables. In this article, we will discuss logical operators in Python definition and also loo
6 min read
Interesting Fact about Python Multi-line Comments
Multi-line comments(comments block) are used for description of large text of code or comment out chunks of code at the time of debugging application.Does Python Support Multi-line Comments(like c/c++...)? Actually in many online tutorial and website you will find that multiline_comments are available in python(""" or '''). but let's first look at
3 min read
G-Fact | All palindromes with an even number of digits are divisible by 11
The statement "All palindromes with an even number of digits are divisible by 11" is a well-known property in number theory and mathematics. It is an intriguing characteristic of palindromic numbers, which are numbers that read the same forwards and backward. In this context, even-digit palindromes are those numbers with an even number of digits th
7 min read
Fun Fact Generator Web App in Python
In this article, we will discuss how to create a Fun Fact Generator Web App in Python using the PyWebio module. Essentially, it will create interesting facts at random and display them on the web interface. This script will retrieve data from uselessfacts.jsph.pl with the help of GET method, and we will use the requests and the JSON module to acqui
3 min read
Compute element-wise logical AND, OR and NOT of tensors in PyTorch
In this article, we are going to see how to compute element-wise logical AND, OR, and NOT of given tensors in PyTorch. We can compute this by using the torch.logical_and(), torch.logical_or(), and torch.logical_not() methods. Let's discuss all of them one by one. Compute element-wise with logical AND torch.logical_and() - This method is used to com
4 min read
Python Bitwise Operators
Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic and logical computations. The value the operator operates on is known as the Operand.  Python Bitwise OperatorsPython bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into
6 min read
not Operator in Python | Boolean Logic
Python not keyword is a logical operator that is usually used to figure out the negation or opposite boolean value of the operand. The Keyword 'not' is a unary type operator which means that it takes only one operand for the logical operation and returns the complementary of the boolean value of the operand. For example, if we give false as an oper
5 min read
GFact | Why Printing Boolean in C++ Display as 0 and 1
Have you ever tried to print some boolean value in the cout section of your code? If yes, then you must have got the output as 0 or 1. But what hapenned to the Boolean value? Why didn't it got printed in the first place? How to get print the boolean value as it is in the output section? What happens when printing Boolean value in C++?Consider the f
2 min read
Python | Print unique rows in a given boolean matrix using Set with tuples
Given a binary matrix, print all unique rows of the given matrix. Order of row printing doesn't matter. Examples: Input: mat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]] Output: (1, 1, 1, 0, 0) (0, 1, 0, 0, 1) (1, 0, 1, 1, 0) We have existing solution for this problem please refer link. We can solve this problem in python
2 min read
Return a boolean array which is True where the string element in array ends with suffix in Python
In this article, we are going to see how we will return a boolean array which is True where the string element in the array ends with a suffix in Python. numpy.char.endswith() numpy.char.endswith() return True if the elements end with the given substring otherwise it will return False. Syntax : np.char.endswith(input_numpy_array,'substring') Parame
2 min read
Scala short ==(x: Int): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The ==(x: Int) method is utilized to return true if this value is equal to x, false otherwise. Method Definition: def ==(x: Int): Boolean Return Type: It returns true if this value is equal to x, otherwise false. Example #1: // Scala program of
1 min read
Boolean Fields in Serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
4 min read
Understanding Boolean Logic in Python 3
Booleans are simple and easy to use concepts that exist in every programming language. A boolean represents an idea of "true" or "false." While writing an algorithm or any program, there are often situations where we want to execute different code in different situations. Booleans help our code to do just that easy and effective. More often, a bool
3 min read
Python EasyGUI – Boolean Box
Boolean Box : It is used to display a window having a multiple options i.e buttons in EasyGUI, it can be used where there is a need to get if the first selection option as it returns 1 for button having index 0 and for other button it returns 0, it is slightly different from index box, below is how the boolean box looks like In order to do this we
3 min read
How to invert the elements of a boolean array in Python?
Given a boolean array the task here is to invert its elements. A boolean array is an array which contains only boolean values like True or False, 1 or 0. Input : A=[true , true , false] Output: A= [false , false , true] Input: A=[0,1,0,1] Output: A=[1,0,1,0] Method 1: You can use simple if else method to invert the array. In the implementation show
2 min read
How to parse boolean values with `argparse` in Python
Command-line arguments are a powerful feature of many programming languages, including Python. They allow developers to specify options or parameters when running a script, making it more flexible and customizable. However, the process of parsing these arguments can be a tedious and error-prone task if done manually. The 'argparse' module in Python
5 min read
How to Return a Boolean Array True Where the String Array Ends with Suffix Using NumPy?
In this article, we will discuss how to return a boolean array that is True where the string element in the array ends with a suffix using NumPy in Python. Example: Check the array ends with Com Input: person_1@abc.com Output: True Input: person_3@xyz.co Output: False In Python, numpy.char module provides a set of vectorized string operations for a
2 min read
Python - Boolean Array in NumPy
In this article, I'll be explaining how to generate boolean arrays in NumPy and utilize them in your code. In NumPy, boolean arrays are straightforward NumPy arrays with array components that are either "True" or "False." Note: 0 and None are considered False and everything else is considered True. Examples: Input: arr = [1, 0, 1, 0, 0, 1, 0]Output
3 min read
Boolean Data Type
In programming languages, we have various data types to store different types of data. Some of the most used data types are integer, string, float, and boolean. The boolean data type is a type of data that stores only two types of values i.e. True or False. These values are not case-sensitive depending upon programming languages. The name Boolean c
13 min read
Python Boolean
Python boolean type is one of the built-in data types provided by Python, which represents one of the two values i.e. True or False. Generally, it is used to represent the truth values of the expressions. Example Input: 1==1Output: True Input: 2<1 Output: FalsePython Boolean TypeThe boolean value can be of two types only i.e. either True or Fals
8 min read
Flipping the boolean values in a Python list
Flipping boolean values in a list involves changing True to False and False to True. This operation is straightforward in Python and can be accomplished using various methods. In this article, we'll explore different techniques to flip boolean values in a list in Python. 1. Using List ComprehensionList comprehension is a concise way to create lists
3 min read
What is new in Data Interpretation and Logical Reasoning in CAT 2019 ?
The CAT exam is a computer-based exam in India for admission into the MBA programs of various management institutes of the country such as IIM’s, FMS, DMS, , etc. CAT is organized by one of the IIM’s on a rotational basis and consequently, it is notorious for changing the exam schedule or pattern on a regular basis. Currently, CAT is divided into t
6 min read
PyQt5 QSpinBox - Getting Horizontal Logical DPI value
In this article we will see how we can get the horizontal resolution of the device in dots per inch(DPI) of the spin box. Logical dots per inch are used to convert font and user interface elements from point sizes to pixel sizes, and might be different from the physical dots per inch. Note : If the horizontal logical DPI doesn't equal to the physic
2 min read
PyQt5 QSpinBox - Getting Vertical Logical DPI value
In this article we will see how we can get the vertical resolution of the device in dots per inch(DPI) of the spin box. Logical dots per inch are used to convert font and user interface elements from point sizes to pixel sizes, and might be different from the physical dots per inch. Note : If the vertical logical DPI doesn't equal to the physical v
2 min read
NumPy Array - Logical Operations
Logical operations are used to find the logical relation between two arrays or lists or variables. We can perform logical operations using NumPy between two data. Below are the various logical operations we can perform on Numpy arrays: AND The numpy module supports the logical_and operator. It is used to relate between two variables. If two variabl
4 min read
What are the Logical Expressions in Sympy?
SymPy is a symbolic mathematics Python package. Its goal is to develop into a completely featured computer algebra system while keeping the code as basic as possible to make it understandable and extendable. The package is entirely written in python language. Logical expressions in sympy are expressed by using boolean functions. sympy.basic.boolean
7 min read
Logical Operations on String in Python
For strings in python, boolean operators (and, or, not) work. Let us consider the two strings namely str1 and str2 and try boolean operators on them: C/C++ Code str1 = '' str2 = 'geeks' # repr is used to print the string along with the quotes # Returns str1 print(repr(str1 and str2)) # Returns str1 print(repr(str2 and str1)) # Returns str2 print(re
2 min read
Merging and Updating Dictionary Operators in Python 3.9
Python 3.9 is still in development and scheduled to be released in October this year. On Feb 26, alpha 4 versions have been released by the development team. One of the latest features in Python 3.9 is the merge and update operators. There are various ways in which Dictionaries can be merged by the use of various functions and constructors in Pytho
3 min read
Article Tags :
Practice Tags :