Quick Overview
An empty dict is falsy, so if not d: is the idiomatic check. d == {} is true for it as well, but cannot tell an empty dict from None: only is None does that.
Create a function is_empty(dictionary) that returns True if a dictionary is empty, and False otherwise.
Dictionaries are Python's key-value lookup data structure. Checking if a dictionary contains data before reading keys prevents runtime errors.
An empty dictionary {} is falsy in Python. You can check not dictionary or len(dictionary) == 0:
def is_empty(dictionary):
return len(dictionary) == 0
# Pythonic Truthiness Alternative
def is_empty_pythonic(dictionary):
return not dictionary
# Testing our function
print(is_empty({})) # Output: True
print(is_empty({"a": 1})) # Output: False
print(is_empty_pythonic({})) # Output: True
{} (Length 0) evaluates to False in boolean context.True.dict["key"] from an unverified dictionary raises a KeyError. Use dict.get("key", fallback) for safe property access!Use dict.get() for safe property reads. Next, let's repeat list items N times!
A function with no return hands back None, so a forgotten one surfaces as a TypeError at the call site rather than at the line that actually caused it.
minutes * 60 returns an int when given an int, while / always produces a float regardless of the operands. Multiplication preserves the type; division does not.
base * height / 2 always yields a float in Python 3 because / never returns an int, even for whole numbers. // floors instead, which is almost never what an area wants.