Data Structures
Python Conditionals/Boolean Explained: Part 6
Conditional statements and Boolean values in Python, essential for controlling the flow of your programs.
Ryan McBride
Ryan McBride
alt

Source: Jon Tyson on Unsplash

1. If Statements (Basic Conditionals)

The if statement is the fundamental way to execute code conditionally. The code inside the if block runs only if the condition evaluates to True.


 language = "python"
 if language == "python":
  print("Language is Python") # This will be executed
 
 if True:
  print("This will always print")
 
 if False:
  print("This will never print")
 

2. Boolean Values and Comparisons

Boolean values are True or False. Conditional statements rely on expressions that evaluate to a Boolean value.

Common comparison operators:

  • == (equal to)
  • != (not equal to)
  • > (greater than)
  • < (less than)
  • >= (greater than or equal to)
  • <= (less than or equal to)
  • is (object identity)

 x = 5
 y = 10
 
 print(x == y)  # Output: False
 print(x != y)  # Output: True
 print(x < y)  # Output: True
 

3. Else Statements

The else statement provides an alternative block of code to execute when the if condition is False.


 language = "java"
 if language == "python":
  print("Language is Python")
 else:
  print("No match")  # Output: No match
 

4. Elif Statements (Else If)

elif (else if) allows you to check multiple conditions in sequence.


 language = "java"
 if language == "python":
  print("Language is Python")
 elif language == "java":
  print("Language is Java") # Output: Language is Java
 else:
  print("No match")
 

5. Boolean Operations (And, Or, Not)

Boolean operators combine or modify conditions.

  • and: Both conditions must be True.
  • or: At least one condition must be True.
  • not: Negates a condition.

 user = "admin"
 logged_in = True
 
 if user == "admin" and logged_in:
  print("Admin page") # Output: Admin page
 
 if user == "admin" or logged_in:
  print("Admin page or logged in") # Output: Admin page or logged in
 
 if not logged_in:
  print("Please log in")
 

6. Object Identity (is Keyword)

== checks for equality of values, while is checks if two variables refer to the same object in memory.


 a = [1, 2, 3]
 b = [1, 2, 3]
 
 print(a == b)  # Output: True (same values)
 print(a is b)  # Output: False (different objects)
 
 b = a
 print(a is b)  # Output: True (same object)
 
 print(id(a))
 print(id(b))
 
 
 
 
 

7. Truthiness and Falsiness in Python

Certain values implicitly evaluate to False:

  • False
  • None
  • Zero of any numeric type (0, 0.0)
  • Empty sequences ("", [], ())
  • Empty mappings ({})

Everything else generally evaluates to True.


 condition = ""
 if condition:
  print("Evaluated to True")
 else:
  print("Evaluated to False") # Output: Evaluated to False
 
 condition = "test"
 if condition:
  print("Evaluated to True") # Output: Evaluated to True
 else:
  print("Evaluated to False")