Python bool Lab
Lab: The Logic Gatekeeper
Run this script to see "Short-Circuiting" and "Truthy/Falsy" in action:
# 1. Truthy/Falsy test
test_items = [0, "", [], None, "Hello", 42]
for item in test_items:
print(f"Value: {item} | Boolean: {bool(item)}")
# 2. Short-Circuit Security Logic
def check_heavy_database():
print("!!! Database Query Running !!!")
return True
is_admin = False
# Because is_admin is False, the database function NEVER runs! (Efficiency)
if is_admin and check_heavy_database():
print("Admin access granted.")
else:
print("Access denied.")
Lab 1: The "Toggle" Switch (Beginner)
Scenario: You are building a "Dark Mode" feature for http://devsecopsguru.in. Every time the user clicks a button, the mode should switch.
-
Task: Create a variable
is_dark_mode = False. Write a line of code that flips it toTrue, and then back toFalseif run again. -
Hint: Use the
notoperator.
is_dark_mode = False
# Click 1
is_dark_mode = not is_dark_mode
print(f"Dark Mode: {is_dark_mode}") # True
# Click 2
is_dark_mode = not is_dark_mode
print(f"Dark Mode: {is_dark_mode}") # False
Lab 2: The Default Value Pattern (Intermediate)
Scenario: You are processing user configurations. If the user didn't provide a name, you want to use "Guest".
-
Task: Use the
oroperator to set a default value. -
Concept: The
oroperator returns the first "Truthy" value it finds.
user_input = "" # User left it empty (Falsy)
# The Master Pattern
display_name = user_input or "Guest"
print(display_name) # Output: Guest
Lab 3: Short-Circuit Safety (Advanced)
Scenario: You are checking if the first user in a database list is "Admin".
-
Task: Safely check
users[0] == 'admin'without crashing if the list is empty. -
Challenge: If
usersis[], accessingusers[0]throws an error. -
Solution: Use
andshort-circuiting.
users = [] # Empty list
# Safe check
if users and users[0] == 'admin':
print("Welcome Admin")
else:
print("No admin found")
# Result: No error, just prints "No admin found"
Lab 4: The "All or Nothing" Validator (Intermediate)
Scenario: You are building a deployment pipeline for http://devsecopsguru.in. A deployment should proceed only if all security checks pass.
-
The Old Way: Writing a loop to check every item in a list and setting a flag.
-
The Master Way: Using the built-in
all()function. -
Task:
-
Create a list of check results:
checks = [True, True, False, True]. -
Use
all(checks)to verify if the deployment is safe. -
Create a second list:
flags = [False, False, True, False]. -
Use
any(flags)to detect if at least one error flag is raised.
security_checks = [True, True, True, True]
error_flags = [False, False, True, False] # Third flag is an error
# all() returns True only if EVERY item is True
is_safe = all(security_checks)
# any() returns True if AT LEAST ONE item is True
has_errors = any(error_flags)
print(f"Deployment Safe: {is_safe}") # True
print(f"System has Errors: {has_errors}") # True
Lab 5: Boolean Arithmetic (Data Science Trick)
Scenario: You have a dataset of 1,000 server ping results (True for success, False for fail). You need to count how many servers are online.
-
The Concept: Since
True == 1andFalse == 0, you can sum booleans directly. -
Task:
-
Create a list:
pings = [True, False, True, True, False]. -
Calculate the total online servers using
sum(). -
Calculate the success rate percentage.
pings = [True, False, True, True, False]
# Summing the list treats True as 1 and False as 0
online_count = sum(pings) # Result: 3
total_servers = len(pings)
uptime_percentage = (online_count / total_servers) * 100
print(f"Online: {online_count}/{total_servers} ({uptime_percentage}%)")
Lab 6: The Operator Precedence Trap (Advanced)
Scenario: You are debugging a logic error in an access control script. A user is being denied access even though they should be allowed.
-
The Problem:
not A or Bis not the same asnot (A or B). -
Task:
-
Set
is_admin = Falseandhas_ticket = True. -
Run Logic A:
not is_admin or has_ticket. -
Run Logic B:
not (is_admin or has_ticket). -
The Analysis:
-
Logic A: Evaluates
(not is_admin)first ->True. ThenTrue or True->True. -
Logic B: Evaluates
(is_admin or has_ticket)first ->True. Thennot True->False. -
Architect Rule: Always use parentheses
()to make your intention explicit. Do not rely on memorizing precedence tables.
Lab 7: Bitwise vs. Logical Operators (Common Pitfall)
Scenario: A developer uses & instead of and to combine conditions. It works sometimes, but fails on others.
-
The Concept:
-
and,or,notare Logical Operators (Short-circuiting). -
&,|,~are Bitwise Operators (Mathematical bit manipulation). -
Task: Compare the behavior of integers vs booleans.
# Example 1: With Booleans (They act similarly)
print(True and False) # False
print(True & False) # False (1 & 0 = 0)
# Example 2: With Numbers (The DANGER zone)
# Logical 'and' checks if both are non-zero.
# Since 5 is truthy and 6 is truthy, it returns the last value (6).
print(5 and 6) # Output: 6
# Bitwise '&' compares bits (0101 & 0110 = 0100)
print(5 & 6) # Output: 4
Lab 8: Custom Object Truthiness (Architect Level)
Scenario: You have a custom class ServerQueue. You want to check if queue: to see if it has pending jobs, just like a standard list.
-
The Solution: Implement the
__bool__(or__len__) magic method. -
Task: Create a class that returns
Falseif the load is 0, andTrueotherwise.
class ServerQueue:
def __init__(self, load):
self.load = load
# This magic method controls truthiness
def __bool__(self):
return self.load > 0
# Usage
empty_queue = ServerQueue(0)
busy_queue = ServerQueue(50)
if empty_queue:
print("Processing jobs...") # Won't run
else:
print("Queue is sleep mode.") # Will run
if busy_queue:
print("Processing jobs...") # Will run