⬅ Previous Topic
Switch Case LogicNext Topic ⮕
Loops - For, While, Nested Loops⬅ Previous Topic
Switch Case LogicNext Topic ⮕
Loops - For, While, Nested LoopsIn programming, especially when dealing with conditional statements, values are evaluated as either truthy
or falsy
. These evaluations determine whether a block of code runs or is skipped. Truthy values act like true
, and falsy values act like false
in a conditional context.
value = "welcome"
if value:
print("Value is truthy")
else:
print("Value is falsy")
Value is truthy
count = 0
if count:
print("Count is truthy")
else:
print("Count is falsy")
Count is falsy
When writing conditions, knowing what values count as false can help prevent bugs. For example, accidentally treating an empty string or zero as valid data can cause unintended behavior.
items = []
if items:
print("There are items")
else:
print("List is empty")
List is empty
What do you think happens when the variable contains an empty string?
Answer: An empty string is evaluated as falsy, so the else
block will run.
is_empty = ""
if not is_empty:
print("The variable is empty")
The variable is empty
When checking if a variable has a "real" value (i.e., not null, not zero, not empty), you can use the variable directly in a conditional. But be cautious: sometimes you want to differentiate between 0
(which is falsy) and something truly invalid like null
.
0
, ""
, null
, false
.if
, while
, etc., gets executed.Q1: Is the number -1
truthy or falsy?
A: Truthy
Q2: What happens if you evaluate null
in a conditional?
A: It is falsy, so the conditional will treat it as false
.
⬅ Previous Topic
Switch Case LogicNext Topic ⮕
Loops - For, While, Nested LoopsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.