Coding Now – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 9667708830
Back to Python Notes
Topic #4

If Else in Python

What Is Conditional Logic?

Conditional statements let your program make decisions and run different code depending on whether a condition is True or False. Python uses if, elif, and else for this.

The if Statement

age = 20

if age >= 18:
    print("You are an adult")

Python uses indentation (not curly braces) to define which code belongs inside the if block. This is a strict rule — inconsistent indentation causes an error.

if...else

age = 15

if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")

if...elif...else

Use elif ("else if") to check multiple conditions in sequence:

marks = 75

if marks >= 90:
    print("Grade A")
elif marks >= 75:
    print("Grade B")
elif marks >= 50:
    print("Grade C")
else:
    print("Fail")

Python checks each condition top to bottom and stops at the first one that's True — the rest are skipped.

Nested if Statements

age = 25
has_ticket = True

if age >= 18:
    if has_ticket:
        print("Entry allowed")
    else:
        print("Buy a ticket first")
else:
    print("Not old enough to enter")

Short-Hand if (One-Liner)

age = 20
if age >= 18: print("Adult")

Ternary / Conditional Expression

A compact way to assign a value based on a condition, all in one line:

age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)   # Adult

Combining Conditions

age = 25
income = 50000

if age >= 18 and income >= 30000:
    print("Eligible for loan")
else:
    print("Not eligible")

Truthy and Falsy Values

Python treats certain values as "falsy" even without an explicit comparison — 0, 0.0, an empty string, [], {}, (), and None are all treated as False in an if condition. Everything else is "truthy":

name = ""

if name:
    print("Name provided")
else:
    print("Name is empty")   # This runs — empty string is falsy

Key Takeaways

  • Python uses indentation, not braces, to define if blocks — be consistent
  • elif lets you check multiple conditions; only the first matching block runs
  • The ternary form x if condition else y is a compact one-line alternative
  • Empty values (0, empty string, [], None) are treated as falsy in conditions

Want to go beyond the notes?

Join CodingNow's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →