Introduction
Python uses truthy and falsy values to decide if something is true or false in conditions, making decisions easy and natural.
Jump into concepts and practice - no test required
if value: # runs if value is truthy else: # runs if value is falsy
if 0: print("This won't print") else: print("Zero is falsy")
if "hello": print("Non-empty string is truthy")
if []: print("This won't print") else: print("Empty list is falsy")
if None: print("This won't print") else: print("None is falsy")
values = [0, 1, "", "text", [], [1,2], None, True, False] for v in values: if v: print(f"{repr(v)} is truthy") else: print(f"{repr(v)} is falsy")
falsy in Python?False in conditions. Common falsy values include None, 0, empty sequences like [], '', and empty collections like {}.[] is an empty list, which is falsy. Options B, C, and D are non-empty and thus truthy.[] -> Option Ax is falsy in Python?if not x: which tests if x behaves like False in a boolean context.x to False but misses other falsy values like 0 or ''. if x is False: checks identity with False, which is too strict. if x = False: has a syntax error (= instead of ==). if not x: is the correct idiomatic way.if not x: to check falsy [OK]values = [0, 1, '', 'Python', [], [1, 2]] result = [bool(v) for v in values] print(result)
val is falsy, but it always prints "Truthy". What is the error?val = 0
if val == False:
print("Falsy")
else:
print("Truthy")val == False only matches if val equals exactly False or behaves equal to it. But some falsy values like 0 compare equal to False, so this seems correct here.0 == False is True, so it should print "Falsy". If it prints "Truthy", likely the code is different or the question expects the explanation that comparing with False is not reliable for all falsy values like empty containers or None.data = [0, 1, '', 'text', [], [1], None]. Which code snippet correctly creates a new list with only truthy values?if x which keeps values that behave like True.if x, which is correct. filtered = [x for x in data if x == True] checks x == True, which excludes truthy but not exactly True values (like 1). filtered = [x for x in data if bool(x) == False] keeps falsy values (bool(x) == False). filtered = [x for x in data if x is not False] excludes only False but keeps other falsy values like 0 or ''.