Python Booleans, None & Console I/O
The bool data type holds True or False. In Python, bool is a subclass of int (where True == 1 and False == 0):
# Boolean flags representing user status:
is_logged_in = True
has_premium_access = False
print("Logged in status:", is_logged_in)
print("Premium access:", has_premium_access)
# In Python arithmetic, True acts as 1 and False acts as 0:
print("True + True equals:", True + True) # 2
print("True * 50 equals:", True * 50) # 50
Because issubclass(bool, int) is True, booleans participate in arithmetic operations seamlessly.
In Python, empty sequences ("", [], {}), zero numbers (0, 0.0), and None evaluate to Falsy. Everything else evaluates to Truthy:
# An empty shopping cart list is Falsy:
cart = []
if not cart:
print("๐ Your cart is currently empty! Please add items.")
else:
print("Cart items:", cart)
# Adding an item makes the list Truthy:
cart.append("Python Masterclass Book")
if cart:
print("โ
Cart now contains:", cart)
Never write if len(cart) == 0:. The clean Pythonic approach is simply if not cart:.
None represents the absence of a value or null state. Always check for it using if val is None: (not == None):
# A variable representing uninitialized profile data:
user_address = None
if user_address is None:
print("Address has not been provided yet.")
else:
print("Delivery Address:", user_address)
None is a singleton object in memory. is None checks pointer address equality in a single CPU instruction, which is faster and safer than == None.
Avoid writing "if is_valid == True:". The Pythonic way is simply "if is_valid:". Similarly, instead of "if is_valid == False:", write "if not is_valid:".
Check if a shopping cart list is empty using Truthy/Falsy evaluation.
cart_items = [] # Empty list is Falsy
if not cart_items:
print("๐ Your cart is empty! Please add items.")
else:
print("Cart has items:", cart_items)
Q Why does bool(True + True) equal True, but True + True equals 2?
In Python, bool inherits from int. In arithmetic expressions (True + True), Python treats them as integers (1 + 1 = 2). When passed to bool(2), any non-zero integer evaluates to True.
Q Why should I use "is None" instead of "== None"?
None is a singleton object in Python memory. is None checks pointer identity in a single CPU instruction without invoking the class equality operator __eq__(), which could be overridden by custom objects.
Q How do I read input securely without displaying passwords on screen?
Use the standard library getpass module: import getpass; pwd = getpass.getpass("Password: ") hides user keystrokes in the terminal.