Booleans in Python

Boolean is an in-built data type of Python. It is used to represent two values: True or False.

For example, 1 <= 2 is true but 1 == 0 is false.

You can check the data type of True and False using the built in type()function.

More about functions in these posts- Functions in Python and Function Arguments in Python

For example-

print(type(True))

print(type(False))

The output-

<class 'bool'>
<class 'bool'>

You cannot assign values to True or False because they are keywords in Python and act like constants. If you assign a value to True or False, it will raise a SyntaxError.

Arithmetic Operations on Boolean Values

In Python, True has the value of 1 and False has the value of 0. Hence, they can be used to perform arithmetic operations.

For example-

print(True+False)

print(True*3)

print(False/2)

The output-

1
3
0

Here’s another way to find if an expression is true or false-

a=7
b=23
print(bool(a=b))

The output-

False

This code gives the output False as 7 is not equal to 23.

Numbers as Booleans

Numbers can be used as Boolean values by using Python’s in-built bool() feature. Any integer, floating-point number or complex number having 0 as its value is considered False, while if they are having value as any positive or negative number then it is considered as True.

For example-

a=0
b=1
c=-9.4

print(bool(a))
print(bool(b))
print(bool(c))

The output-

False
True
True

Booleans created by comparison operators

Booleans can be created by using comparison operators also.

For example-

a=5
b=10

print(a==b)
print(a!=b)
print(a<b)
print(a>b)
print(a<=b)
print(a>=b)

The output-

False
True
True
False
True
False


That is all for today’s post on Booleans in Python. Hope you found it informative and easy to understand. If you have any suggestions or reviews, please consider filling the contact form or comment down below.

Happy coding,
Aarav Iyer

Aarav Iyer

I am a technology and programming enthusiast, currently a high school student. I love drawing and am quite interested in aeronautics and astrophysics too. My favourite pastimes are reading books, blogging and skywatching with my telescope.

Post a Comment

Previous Post Next Post