01. Booleans and logical testing

Python comes in a variety of data types. Before we go over the more interesting data structures (like collections) let's take a brief tour of the primitive data types - booleans, numbers and strings. We'll start with the most basic type - Booleans.

Booleans

Booleans contain just two values - True and False. These values are case-sensitive, so don't forget to uppercase the first letters!

Booleans can be the result of expressions.

>>> 2 < 3
True
>>> 2 > 3
False
>>> 2 < 2 < 1
False

True and False are interchangable with 1 and 0. Additionally, the empty string "" is treated as False, while all other values are equivalent to True. It's best practice to use actual boolean types.

Boolean Operators

Booleans have operators not, and and or that can be used in conjunction with boolean data types.

>>> not True
False
>>> True and False
False
>>> False or True
True

Later on you'll see that booleans are used in conditional statements for flow control. For example, in an if statement, the block of code that becomes execute depends on the boolean value of the expression proceeds the if statement.

Aching back from coding all day?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ reviews)

More Back Problems resources

Learn to be a Pythonista!

Learning Python

Learn to be a Pythonista! Try Python

Get a comprehensive, in-depth introduction to the core Python language with this hands-on book. Based on author Mark Lutz's popular training course, this updated fifth edition will help you quickly write efficient, high-quality code with Python. It's an ideal way to begin, whether you're new to programming or a professional developer versed in other languages.

$ Check price
64.9964.99Amazon 4 logo(279+ reviews)

More Python resources

Ad