🧠 Boolean Definition + Example
🌟 What is a Boolean?
A Boolean is a data type that can only have two possible values:
- True
- False
These values are used to answer questions like:
- “Is this condition met?”
- “Has this event occurred?”
💡 Why are Booleans Important?
Booleans allow programs to make decisions! For example, you can use Booleans to check:
- If a user is logged in
- If a number is positive
- If a file exists
🐍 Boolean Examples in Python
Let’s look at some simple examples and explain each line:
# Example 1: Simple Boolean assignment
is_sunny = True
Explanation:
is_sunny
is a variable that stores a Boolean value. Here, it is set to True, meaning it is sunny.
# Example 2: Boolean from a comparison
is_adult = 18 >= 18
Explanation:
18 >= 18
checks if 18 is greater than or equal to 18. This is True.is_adult
will be assigned the value True.
# Example 3: Using Booleans in an if statement
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult.")
Explanation:
age
is set to 16.if age >= 18:
checks ifage
is at least 18. This is False.- Since the condition is False, the code in the
else
block runs, printing “You are not an adult.”
# Example 4: Boolean operators
is_raining = False
is_cold = True
if is_raining or is_cold:
print("Bring a jacket!")
Explanation:
is_raining
is False,is_cold
is True.or
checks if at least one condition is True. Sinceis_cold
is True, the message “Bring a jacket!” is printed.
🎯 Summary
- Booleans are True or False values.
- They are used for decision making in code.
- You can create Booleans directly, from comparisons, or by combining conditions with operators like
and
,or
, andnot
.
Booleans are everywhere in programming, and understanding them is key to writing effective code!