Open In App

Check for True or False in Python

Last Updated : 18 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Python has built-in data types True and False. These boolean values are used to represent truth and false in logical operations, conditional statements, and expressions.

In this article, we will see how we can check the value of an expression in Python.

Common Ways to Check for True or False

Python provides various ways to check if an expression is evaluated as True or False. Let us see them one by one:

Using bool() Function

The bool() function is an in-build Python function that returns the Boolean value of an expression.

Python
# returns False as 'a' is 0
a = 0
print(bool(a))

# returns True as 5 is greater then 3
b = 5 > 3
print(bool(b))

# returns True as 'c' is True
c = True
print(bool(c))

# returns True as 'f' is not an empty string
d = "GfG"
print(bool(d))

# returns False
e = None
print(bool(e))


Using Comparison Operators

We can use Comparison operator to check if an expression evaluates to True or False. == and != Operator can be used with if condition or while statement to evaluate an expression.

Python
a = 10
b = 10

# checking the value using the equality operator
print(a == b)

# checking the value using inequality operator
print(a != b)

Output
True
False


Using Logical Operators

Logical Operators (and, or, not) allow combining multiple conditions.

Python
a = True
b = False

# Using different logical operators
print(a and b)  # False (both conditions must be True)
print(a or b)   # True (at least one condition is True)
print(not a)    # False (negation of True)

Output
False
True
False


Using Identity Operators

Identity Operator such as 'is' and 'is not' Operator can be used to check if two variables reference the same object in memory. They are particularly useful when you need to check for object identity rather than equality.

Python
a = 10
b = 10

# True (both variables point to the same object)
print(a is b)

# False (both variables point to the same object)
print(a is not b)

Output
True
False



Next Article
Article Tags :
Practice Tags :

Similar Reads