Using Boolean expressions in Python

problem

In Python, we can use Boolean expressions to perform logic and take conditional actions. For example in an if statement, in a while loop, etc.

SOLUTION

First, we have the two binary values for Boolean Algebra:

  • True
  • False

Then, for expressions we have the following three different keywords:

  • not
  • and 
  • or

Also, the following comparison operators

  • >
  • <
  • >=
  • <=
  • ==
  • !=

The above operators are all binary. For example we need a value to the left side of the operator and another value to the right side.

In comparison with the not keyword above that is unary. Meaning, that will accept a value of boolean type and return the opposite value.

Examples:

Using some logic to see if a person is adult or not

				
					age = int(input("Enter age:"))
if age >= 18 then:
	print ("adult") #if True, it will print this
else:
	print("not adult")
				
			
And keyword - truth table
Value Keyword Value Result
True
and
True
True
False
and
True
False
False
and
False
False
Running
and keyword in Python
Or keyword - truth table
Value Keyword Value Result
True
or
True
True
False
or
True
True
False
or
False
False
Running
or keyword in Python
not keyword - Truth table
Value Keyword Result
True
not
False
False
not
True
Running
not keyword in Python
priority of keywords
  1. Not
  2. And
  3. Or

conclusion

In this post we saw a brief introduction to boolean algebra and simple usages in Python. 

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪