Boolean variables and boolean arithmetic in Python (4/100 Days of Python)
Boolean variables are variables that can have one of two values: True
or False
. In Python, you can use the bool
type to create a Boolean variable.
Here’s an example of how to create a Boolean variable in Python:
is_raining = True
is_sunny = False
You can also use the bool()
function to convert other types of variables to Booleans. For example:
print(bool(0)) # False
print(bool(1)) # True
print(bool('hello')) # True
print(bool('')) # False
There are several Boolean operators in Python that allow you to manipulate and test Boolean variables. Here are the most common ones:
and
: ReturnsTrue
if both operands areTrue
, andFalse
otherwiseor
: ReturnsTrue
if at least one operand isTrue
, andFalse
otherwisenot
: Returns the opposite of the operand (i.e.,True
becomesFalse
, andFalse
becomesTrue
)
Here are some examples of using these operators:
print(True and False) # False
print(True and True) # True
print(False or True) # True
print(False or False) # False
print(not True) # False
print(not False) # True
Values of some expressions can be assigned to boolean variables as well:
a = 10
b = 20
greater = a > b # False
smaller = a < b # True
equal = 10 == 10 # True
print(greater, smaller, equal)
This is especially useful in conditional statements, which we will cover in the coming series!
What’s next?
- If you found this story valuable, please consider clapping multiple times (this really helps a lot!)
- Hands-on Practice: Free Python Course — boolean variables
- Full series: 100 Days of Python
- Previous topic: Arithmetic expressions and numeric variables
- Next topic: Conditions in Python