Table of Content
Boolean
Booleans in Python represent truth values: True or False. They are used to control the flow of programs through conditional statements and loops.
Booleans are essential for decision-making in Python, enabling the evaluation of expressions to determine whether they are true or false.
Conditional statement:
python
x = 10
y = 5
if x > y:
print("x is greater than y") # This line will be printed
else:
print("x is not greater than y")
Output:
python
x is greater than y
Boolean operations:
python
a = True
b = False
print(a and b)
print(a or b)
print(not a)
Output:
python
False
True
False
We can use boolean in loops. Let us see in the example below:
python
numbers = [1, 2, 3, 4, 5]
contains_three = False
for num in numbers:
if num == 3:
contains_three = True
break
print(contains_three)
Output:
python
True
In simple terms, booleans in Python are like switches that can be either "on" (True) or "off" (False). They help us make decisions in our code, like whether to do something or not based on certain conditions. They're the building blocks for making our programs smart and responsive.