π§ Boolean Lesson + Example
π§ Boolean Definition + Example
π§ 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_sunnyis 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 >= 18checks if 18 is greater than or equal to 18. This is True.is_adultwill 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:
ageis set to 16.if age >= 18:checks ifageis at least 18. This is False.- Since the condition is False, the code in the
elseblock 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_rainingis False,is_coldis True.orchecks if at least one condition is True. Sinceis_coldis 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!
π Essential Boolean Concepts
Master these fundamentals to ace your quiz!
π’
What is a Boolean?
A boolean is a data type with only two possible values:
β
True
β False
π―
Why Use Booleans?
Booleans help programs make smart decisions based on conditions.
Common Uses:
- β Check if number is positive
- π Verify if file exists
- π Control program flow
π« Types of Boolean Operations
π Direct Assignment
is_sunny = True
π Comparisons
is_adult = age >= 18
β‘ Boolean Operators
The three powerful logical operators!
π€
AND
True only if both are True
True AND True = True
True AND False = False
True AND False = False
π
OR
True if at least one is True
True OR False = True
False OR False = False
False OR False = False
π
NOT
Flips True to False and vice versa
NOT True = False
NOT False = True
NOT False = True