Truthy and Falsy Values
in Control Flow



Understanding Truthy and Falsy

In 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.

Common Falsy Values

Common Truthy Values

Example 1: Truthy in If Condition

value = "welcome"

if value:
    print("Value is truthy")
else:
    print("Value is falsy")

Output:

Value is truthy

Example 2: Falsy with Zero

count = 0

if count:
    print("Count is truthy")
else:
    print("Count is falsy")

Output:

Count is falsy

Why does this matter?

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.

Example 3: Using Collections

items = []

if items:
    print("There are items")
else:
    print("List is empty")

Output:

List is empty

Question:

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.

Example 4: Negating a Falsy Value

is_empty = ""

if not is_empty:
    print("The variable is empty")

Output:

The variable is empty

Pro Tip:

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.

Summary

Mini Quiz

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.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M