Booleans in Python

We offer you a brighter future with FREE online courses - Start Now!!

You would have come across ‘True’ or ‘False’ questions in your examinations. Do you know that these form a data type in Python? We will learn booleans, booleans of the constructs, operation on booleans, and operators that return booleans in Python. So, let’s get started.

Booleans in Python

In Python, the boolean is a data type that has only two values and these are
1. True and
2. False.
Let us first talk about declaring a boolean value and checking its data type.

boolean data type in Python

Declaring a Boolean Value in Python

Like any other value such as a number, string, etc., we can declare a boolean value by assigning it to a variable. For example,

Example of declaring a boolean value:

var=True
print(f"The type of {var} is {type(var)}")

var2=False
print(f"The type of {var2} is {type(var2)}")

Output:

The type of True is <class ‘bool’>

The type of False is <class ‘bool’>

Exceptions in Declaring Booleans in Python

1. Case-sensitive:

An important point to remember is that the first letter of each boolean value is capital and the rest characters are lowercase. But if we make any changes in the letter case we get an error as that word will not belong to a boolean class as shown below.

Example of getting an error on changing case while declaring a boolean:

var=true

Output:

Traceback (most recent call last):
File “<pyshell#4>”, line 1, in <module>
var=true
NameError: name ‘true’ is not defined

2. Using double or single quotes:

Another point to note is that we should not enclose the booleans by single or double-quotes. If we do so, it will be considered as a string. For example,

Example of using quotes while declaring a boolean:

var2="False"
print(f"The type of {var2} is {type(var2)}")

Output:

The type of False is <class ‘str’>

Python bool() function

The bool() function is one of the functions used for data conversion. This function converts the other data types into boolean type. It gives True if the value is not empty or 0, ele False.

Example of using the bool() function:

var_1=bool(4) #boolean of a on zero number
print(f"The type of {var_1} is {type(var_1)}")

var_2=bool([]) #boolean of an empty list
print(f"The type of {var_2} is {type(var_2)}")

Output:

The type of True is <class ‘bool’>

The type of False is <class ‘bool’>

More about Python Booleans

The values True and False are not the built-in functions or constants, but these are keywords in Python. So, these cannot be used as variable names. The below example shows that we get an error in using booleans as identifiers.

Example of getting an error on using booleans as identifiers :
True=3

False=”

Output:

SyntaxError: cannot assign to True

SyntaxError: cannot assign to False

Boolean values of Constructs in Python

The values of other data types are True if they are neither empty nor 0, else they are False. The following values are considered to be False:
1. Numbers: 0,0.0,0j
2. Strings: ”,””
3. Lists, tuples: [],()
4. Dictionary:{}
5. False
6. None
7. Other methods that return either 0 or False

We can check this by applying the bool() function. We will find the boolean values for the data types.

1. Numbers:

The numbers with 0 as the values are considered as False and the others are True.

Example of checking bool() on numbers:

bool(0)

bool(0.0000000000001)

bool(0.0j)

Output:

False

True

False

2. Strings:

Only an empty string is False, the rest of the strings are considered to be True. Even the string with space is True, as space is also a character in Python.

Example of checking bool() on strings:

bool(" ")

bool("")

bool('PythonGeeks')

Output:

True

False

True

3. Lists, tuples, and dictionaries:

These will be boolean False if they do not have any element or they are empty. Else, these are False.

Example of checking bool() on lists, tuples, and dictionaries:

bool(())

bool((1,2))

bool([])

bool(['t'])

bool({})

bool({4:'c'})

Output:

False

True

False

True

False

True

4. Others

Let us check the boolean for the others too.

Example of checking bool():

bool(None)

bool(True)

bool(False)

Output:

False

True

False

Operators that give boolean values

There are many operators that return boolean values like membership operators, comparison, etc. We will see them in this section.

Functions that return boolean values

1. Membership operators

The operators ‘in ‘and ‘not in’ are the two membership operators. The ‘in’ gives True if the element is in the sequence, else returns False. The operator ‘not in’ does the opposite.

Example on membership operators:

'e' in 'PythonGeeks'

5 not in [1,3,4,5.0,8]

6.7 in (1,5,'t')

Output:

True

False

False

2.Comparison Operators

In Python, we have six comparison operators and these are ==,!=,<,<=,>,>=. These give True if the values satisfy the condition of the first operand is

a. equal to the second one for ==

b. not equal the second one for !=

c. less than the second one for <

d. less than or equal to the second one for <=

e. greater than the second one for >

g. f. greater than or equal to the second operand for >=.

Else the boolean False is returned. For example,

Example on comparison operators:

5.0==5

[1,2,3]>[2,3,4]

4.5!=7

'abc'>='ABC'

(1.3,4,78)<(0,5.6,3)

{'a','b'}<={'a','b','d'}

Output:

True

False

True

True

False

True

3. Identity operators

The operators ‘is ‘and ‘is not’ are the two identity operators in Python. The ‘is’ gives True if the elements are equal and are stored in the same memory location, else returns False. The operator ‘is not’ does the opposite.

Example on identity operators:

5.0 is 5

'a' is not 'A'

{1,2,3} is {2,3,1}

Output:

False

True

False

Operations on Booleans in Python

Like we do operations on any other data types, we can do on booleans too. Let us discuss them in this section.

1. Addition :

We can add two or more boolean values using the ‘+’ operator. The True will be considered as 1 and False as 0.

Example on adding boolean values:

True+False #1+0

True+False+False+True #1+0+0+1

True+False+False+True+True #1+0+0+1+1

Output:

1

2

3

2. Subtraction:

Two or more boolean values can be subtracted using the ‘-’ operator. The True value is the same as 1 and the False is 0.

Example on subtracting boolean values:

False-True #0-1

True-False+True #1-0+1

Output:

-1

2

3. Multiplication:

Two or more boolean values can be subtracted using the ‘-’ operator. The True value is the same as 1 and the False is 0.

Example on multiplying boolean values:

True * False #1*0

True * True #1*1

Output:

0

1

4. Division and Integer division

We can divide the booleans using the ‘/’ operator and we get a float value. And we use ‘//’ for the integer division. But we have to note that we cannot divide a number by zero. In math, we either say it is undefined or infinity. Let us see what Python tells us.

Example on dividing boolean values:

True/True #1/1

False/True #0/1

True/False #1/0

True//True #1//1

False//True #0//1

Output:

1.0

0.0

Traceback (most recent call last):
File “<pyshell#56>”, line 1, in <module>
True/False
ZeroDivisionError: division by zero

1

0

5. Modulus, and Exponential:

We use the ‘%’ and ‘**’ for modulus and exponential operation. The below example shows the operations. We cannot use False (0) as the second operator for the modulus operator.

Example of applying modulus and exponential operators on booleans:

True % True #1%1

True%False #1%0

True**False #1**0

True**True #1**1

Output:

0

Traceback (most recent call last):
File “<pyshell#60>”, line 1, in <module>
True%False
ZeroDivisionError: integer division or modulo by zero

1

1

6. Relational Operators:

There are six relational operators in Python and these are ==,!=,<,<=,>,>=. These give either True or False depending on whether the condition of the respective operator is satisfied or not.

Example of applying relational operators on booleans:

True == False #1==0

True>False #1>0

True != True #1!=1

True>=False #1>=0

False<True #1<0

False<=False#0<=0

Output:

False

True

False

True

True

True

7. Bitwise Operators:

In Python we have | (OR), & (AND), ^ (XOR), ~ (NOT), >> (Right Shift), << (Left Shift) as the bitwise operators. Let us see the examples of these.

Example of applying bitwise operators on booleans:

True | False #1|0

False & True #0 &1

False ^ False # 0^0
 
~False #~0

True<<2 #1<<2

False>>3 #0>>3

Output:

True

False

False

-1

4

0

8. Logical Operators:

The operators and, or, not are the logical operators in Python. The ‘and’ gives True if both the operands are True else returns False. The ‘or’ gives True if at least one of the operands is True else returns False. The operator ‘not’ takes works on only one operand and gives True if the operand is either 0/ empty value/ False, or else it returns False.

Example of applying logical operators on booleans:

True and False

False or True

not False

Output:

False

True

True

Interview Questions on Booleans in Python

Q1. Assume there are 5 questions in an Exam. And the results are marked as either True or False. Each question has 2 marks. Find the total score.

Ans. We can use the + operator to find the number of correctly answered questions and multiply the result by 2 to get the final result.

Example of finding the sum of booleans:

Q1=True
Q2=False
Q3=False
Q4=True
Q5=True

marks = 2*(Q1+Q2+Q3+Q4+Q5)
print(marks)

Output:

6

Q2. Write the program to give the output as the second element if the result is False else the first element.

Ans. We know that True is 1 and False is 0. Ans we need the second element (index 1) if the result is False and if True needs the first element (index 0). SO we can give the ‘not’ of the Boolean as an index.

Example of giving boolean as index:

list1=['a','b']
print(list1[not False])

print(list1[not True])

Output:

b

a

Q3. Check if the number lies in the range of 1 and 10 and give the result as True or False.
Ans. below is the example of doing the comparison and logical operations:

num=5
num>=1 and num<=10

num=19
num>=1 and num<=10

Output:

True

False

Q4. Check if the name is present in the list of names.

Ans. We can use the ‘in’ operator to check if the value is present in the list or not as shown below:

list1=['abc','pqr','xyz','uvw']
'xyz' in list1

'ertyh' in list1

Output:

True

False

Q5. Assume the result is True if and only if all the values are True. Write the program to do so without using the logical operators.

Ans. We can use the multiplication operation and then find the boolean of the resulting value as shown below:

val1=True
val2=False
val3=True

res=val1*val2*val3
print(bool(res))

val2=True

res=val1*val2*val3
print(bool(res))

Output:

False

True

Quiz on Booleans in Python

Conclusion

Congratulations! You have added another topic to your Python box.

First, we learned about Python booleans and their declaration. Then we saw boolean values of various data types using the bool() function. After this, we saw operations that result in boolean values and operators we can apply to boolean values.

In the end, we saw some interview questions. Hope you enjoyed it. Happy learning!

Did we exceed your expectations?
If Yes, share your valuable feedback on Google | Facebook


1 Response

  1. NOXIOUS says:

    there is a mistake in operation on boolean section . In multiplication statement subtraction word and operator is written.

Leave a Reply

Your email address will not be published. Required fields are marked *