Understanding and Using Booleans
In this tutorial, you'll learn about booleans, a simple yet powerful data type in Python. Booleans help us answer yes/no questions in our code, such as "Is this true?" or "Does this condition meet the requirement?"
In this tutorial, you'll learn about booleans, a simple yet powerful data type in Python. Booleans help us answer yes/no questions in our code, such as "Is this true?" or "Does this condition meet the requirement?"
1. What Are Booleans?
Booleans represent one of two values:
True
False
These values are often the result of comparisons or conditions in a program.
2. Using Booleans
a. Direct Assignment
You can create a boolean variable by assigning True or False directly.
Example:
is_sunny = True
is_raining = False
print("Is it sunny today?", is_sunny)
Output:
Is it sunny today? True
b. Comparisons
Booleans are often used to compare values using comparison operators:
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
Example:
age = 13
is_teenager = age >= 13 and age <= 19
print("Is the person a teenager?", is_teenager)
Output:
Is the person a teenager? True
c. Logical Operators
You can combine boolean values using logical operators:
and: True if both conditions are true
or: True if at least one condition is true
not: Reverses the boolean value
Example:
is_weekend = True
is_holiday = False
can_relax = is_weekend or is_holiday
print("Can I relax today?", can_relax)
Output:
Can I relax today? True
3. Booleans in Conditional Statements
Booleans are commonly used in if statements to decide what code to run.
Example:
is_hungry = True
if is_hungry:
print("Time to eat!")
else:
print("No need to eat right now.")
Output (if is_hungry is True):
Time to eat!
4. Practice Exercises
Exercise 1: Simple Booleans
Create a program that:
Declares a boolean variable is_hot and sets it to True or False.
Prints "It's hot today!" if is_hot is True.
Exercise 2: Comparisons
Write a program that:
Compares two numbers (e.g., num1 = 15, num2 = 20).
Prints whether num1 is greater than, less than, or equal to num2.
Exercise 3: Logical Operators
Create a program that:
Declares two boolean variables: is_raining and has_umbrella.
Prints "You can go outside!" if you have an umbrella or it’s not raining.
5. Bonus Challenge
Write a program that checks if a student passes a test:
Ask the user for their test score.
If the score is 50 or higher, print "You passed!"
If the score is below 50, print "Try again next time."
Example Output:
Enter your test score: 65
You passed!
6. What’s Next?
Booleans are the foundation of making decisions in Python. Once you’re comfortable with them, you can explore loops and more complex logic!
Great job learning about booleans! 🎉