This content originally appeared on DEV Community and was authored by Rahul Gupta
Welcome to Day 7 of the 100 Days of Python series!
Today, we’re diving into one of the core foundations of decision-making in programming: Booleans and Logical Operators. These help your code think for itself — to make choices, evaluate conditions, and respond accordingly.
Let’s understand how Python makes decisions under the hood.
What You’ll Learn
- What Booleans are
- How Python evaluates conditions
- Logical operators:
and
,or
,not
- How to combine conditions
- Real-world examples
What Is a Boolean?
A Boolean is a data type that has only two possible values:
True
False
These are case-sensitive (true
and false
will raise an error).
You can assign them to variables:
is_sunny = True
is_raining = False
Conditions That Return Booleans
Python evaluates expressions and returns either True
or False
.
x = 5
print(x > 3) # True
print(x == 10) # False
print(x != 7) # True
Common Comparison Operators:
Operator | Meaning | Example | Result |
---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 3 != 2 |
True |
> |
Greater than | 4 > 2 |
True |
< |
Less than | 5 < 3 |
False |
>= |
Greater than or equal | 5 >= 5 |
True |
<= |
Less than or equal | 2 <= 1 |
False |
Logical Operators
Logical operators allow you to combine multiple conditions.
1⃣ and
– All conditions must be True
age = 20
is_student = True
print(age > 18 and is_student) # True
2⃣ or
– At least one condition must be True
print(age > 18 or is_student == False) # True
3⃣ not
– Reverses the boolean value
print(not is_student) # False
Real-World Example
Let’s say we’re checking if someone can get a discount:
age = 16
has_coupon = True
if age < 18 or has_coupon:
print("You get a discount!")
else:
print("Sorry, no discount.")
Output:
You get a discount!
Bonus: Booleans with Strings and Numbers
Python treats some values as False
, like:
- Empty strings:
""
- Zero:
0
,0.0
- Empty lists, dicts, sets:
[]
,{}
,set()
None
Everything else is considered True
.
print(bool("")) # False
print(bool("Hi")) # True
print(bool(0)) # False
print(bool(42)) # True
print(bool([])) # False
This becomes useful in conditions:
name = ""
if not name:
print("Please enter your name.")
Recap
Today you learned:
- The Boolean values
True
andFalse
- Comparison operators:
==
,!=
,>
,<
,>=
,<=
- Logical operators:
and
,or
,not
- How to evaluate and combine conditions
- Real-world usage in if-statements
This content originally appeared on DEV Community and was authored by Rahul Gupta