Any object can be used as a condition. Python converts it with bool(): falsy values are None, False, zeros (0, 0.0), empty strings and empty collections; everything else is truthy.
for v in [0, 0.0, "", [], {}, set(), None, False]:
print(bool(v), end=" ") # False False False False False False False False
print()
for v in [1, -3, "0", [0], " "]:
print(bool(v), end=" ") # True True True True True
print()
name = ""
print(name or "anonymous") # anonymous (or returns the first truthy value)
Note that "0" and " " are truthy: they are non-empty strings. Thanks to this you write if items: instead of if len(items) > 0:.
Converting without the program failing
int("abc") raises ValueError. When the text comes from the user, wrap the conversion in try/except and decide what to do if it fails: return None, ask for another value or use a default.
def to_int(text):
try:
return int(text)
except ValueError:
return None
print(to_int("42")) # 42
print(to_int("4.2")) # None
print(to_int("")) # None
int()accepts signs and surrounding spaces, but not decimals ("3.5"): usefloat()first for that.- Check the result with
is None, not withif result:, because0is falsy too. - Always catch the specific exception (
ValueError), never a bareexcept:.
You practice it in Truthy or falsy and Safe conversion to integer.