In Python, a Boolean represents one of two values: True or False. Booleans are used in conditions, loops, and logical expressions to control the flow of a program.
Internally, Booleans are a special type that behave like the numbers 1 (for True) and 0 (for False) in many situations, but they are mainly used to represent logical states.
True and False.if statements, loops, and decision-making logic.0, 0.0, "" (empty string), [], (), {} (empty collections), and None.Python provides three main logical operators for Booleans:
and – returns True if both operands are True.or – returns True if at least one operand is True.not – returns the opposite Boolean value (inverts it).Booleans are often produced using comparison operators like:
== – equal to!= – not equal to>, < – greater than, less than>=, <= – greater than or equal to, less than or equal toYou can store Boolean values directly in variables using True and False.
a = True
b = False
print(a)
print(b)
print(type(a))
True False <class 'bool'>
Here, a and b are Boolean variables, and type(a) confirms that they are of type bool.
Use logical operators to combine or invert Boolean values.
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
x and y is False because both need to be True, but y is False.x or y is True because at least one of them (x) is True.not x inverts True to False.Comparisons between values result in Boolean answers:
a = 5
b = 10
print(a == b) # False
print(a != b) # True
print(a < b) # True
print(a >= 5) # True
a == b is False because 5 is not equal to 10.a != b is True because 5 is different from 10.a < b is True because 5 is less than 10.a >= 5 is True because 5 is greater than or equal to 5.Booleans are most commonly used in if statements to decide which block of code should run.
is_raining = True
if is_raining:
print("Take an umbrella!")
else:
print("No umbrella needed.")
Take an umbrella!
If is_raining is True, the first message prints. If it were False, the else part would run instead.
is_active, has_access, or is_logged_in.0, empty strings, None, and empty collections are treated as False in conditions.if is_raining:if is_raining == True:"True" (string) is not the same as True (Boolean).is_student and has_id_card) and print the results of and, or, and not on them.if statement using a Boolean variable (e.g., is_logged_in) to print different messages for logged-in and guest users.>, <=, ==, !=) on numbers and strings and print their Boolean results.bool() of different values: bool(0), bool(1), bool(""), bool("hello"), bool([]), bool([1, 2, 3]) and observe which ones are True or False.