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?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources

Learn to be a Pythonista!

Programming for Beginners

Learn to be a Pythonista! Try Python

This book doesn't make any assumptions about your background or knowledge of Python or computer programming. You will be guided step by step using a logical and systematic approach. As new concepts, commands, or jargon are encountered they are explained in plain language, making it easy for anyone to understand.

$ Check price
24.9924.99Amazon 4.5 logo(124+ reviews)

More Python resources

Ad