Python Booleans 🎯

beginner
25 min

Python Booleans 🎯

Welcome to our deep dive into Python Booleans! In this comprehensive guide, we'll explore this fundamental aspect of Python programming, making it easy for both beginners and intermediates to understand.

What are Booleans? 📝

Booleans, named after the English mathematician George Boole, are the foundation of modern digital logic. In Python, they represent True or False values, helping us make decisions in our code.

Understanding Truth and Falsehood 💡

  • True is a Boolean representing true statements.
  • False is a Boolean representing false statements.

Operators for Comparison 💡

Python provides several operators to compare values, which ultimately return a True or False value:

  • ==: Equal to
  • !=: Not equal to
  • >: Greater than
  • <: Less than
  • >=: Greater than or equal to
  • <=: Less than or equal to

Basic Boolean Expressions 💡

Let's create some basic Boolean expressions using comparison operators:

python
# Simple comparison x = 10 y = 20 print(x < y) # Output: True # Combining comparisons z = 5 print((x < y) and (z > 3)) # Output: True # Using the not operator print(not(x < y)) # Output: False

Logical Operators 💡

Logical operators help combine Boolean expressions, making our code more complex and powerful:

  • and: Returns True if both expressions are True
  • or: Returns True if at least one expression is True
  • not: Reverses the truth value of an expression

Let's explore logical operators with some examples:

python
# Using and operator x = 10 y = 20 z = 5 print((x < y) and (z > 3)) # Output: True # Using or operator print((x < y) or (z < 3)) # Output: True # Using not operator print(not(x < y)) # Output: False

Booleans in Decision Making 💡

We can use Booleans and comparison operators to make decisions in our code:

python
x = 10 if x < 15: print("x is less than 15")

Boolean Functions 💡

Python provides some built-in functions that return Boolean values:

  • bool(): Converts any value to a Boolean. Empty values like "", [], (), None, and 0 return False, while all other values (including zeroes and empty lists/tuples/dictionaries) return True.
  • len(): Returns the length of a list, string, or tuple. If the length is greater than zero, it returns True.

Let's try these functions:

python
# Using bool() x = 0 print(bool(x)) # Output: False # Using len() my_list = [] print(len(my_list)) # Output: 0, and thus it returns False

Quiz 📝

Quick Quiz
Question 1 of 1

What will the following code print?