Boolean variables and boolean arithmetic in Python (4/100 Days of Python)

Martin Mirakyan
2 min readJan 5, 2023

--

Day 4 of the “100 Days of Python” blog post series covering boolean variables and boolean arithmetic

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: Returns True if both operands are True, and False otherwise
  • or: Returns True if at least one operand is True, and False otherwise
  • not: Returns the opposite of the operand (i.e., True becomes False, and False becomes True)

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?

--

--

Martin Mirakyan
Martin Mirakyan

Written by Martin Mirakyan

Software Engineer | Machine Learning | Founder of Profound Academy (https://profound.academy)

No responses yet