Home Blogs All Courses
python c OA ( Online Assessment ) Amazon Web Services (AWS) leetcode dsa algorithms java Machine learning
Get Referral
Login Sign Up

python › Conditional statements in Python

Python if, elif, else: Conditional Statements Explained with Examples

phoolchandra  ·  Oct 23, 2026  · Published


Every useful program makes decisions: if the password is correct, log in; if marks are above 90, give grade A; otherwise show an error. In Python, these decisions are written with if, elif and else. In this blog you will learn conditional statements from the basics to pro tricks like the ternary operator and match-case.

Watch the video first, then use this blog as your notes. Every section has runnable examples, and at the end you will find a "Predict the Output" quiz, practice challenges, a self-check list, interview questions and a quick summary.

How to use this blog: Open the Python shell (type python in your terminal) or any online Python editor and type every example yourself. Change the values, break the code and see what happens — that is how concepts really stick.

1. What are Conditional Statements?

Conditional statements let your program run different code depending on whether a condition is True or False. Think of a traffic signal: red → stop, yellow → slow down, green → go.

condition?
          /          \
       True          False
        |              |
   run if-block   run else-block
          \          /
         rest of program

2. Comparison and Logical Operators

Conditions are built using these operators. Each returns True or False.

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than7 > 9False
<Less than2 < 4True
>=Greater than or equal5 >= 5True
<=Less than or equal3 <= 1False
andBoth must be True5 > 2 and 3 > 1True
orAt least one True5 > 9 or 3 > 1True
notReverses the resultnot 5 > 2False
inMembership"a" in "cat"True

3. The if Statement

age = 20
if age >= 18:
    print("You are eligible to vote")
print("Program finished")

Rules: the condition ends with a colon :, and the block below is indented (4 spaces). All indented lines belong to the if.

4. if-else — Two Paths

number = int(input("Enter a number: "))
if number % 2 == 0:
    print(number, "is Even")
else:
    print(number, "is Odd")

5. if-elif-else — Many Paths

Use elif (short for "else if") to check several conditions. Python checks them top to bottom and runs only the first one that is True.

marks = 82

if marks >= 90:
    grade = "A"
elif marks >= 75:
    grade = "B"
elif marks >= 60:
    grade = "C"
elif marks >= 33:
    grade = "D"
else:
    grade = "Fail"

print("Grade:", grade)      # Grade: B

Order matters: If you check marks >= 33 first, a student with 95 marks would get grade D! Always put the most specific / highest condition first.

6. Nested if — A Decision Inside a Decision

age = 25
has_licence = True

if age >= 18:
    if has_licence:
        print("You can drive")
    else:
        print("Get a licence first")
else:
    print("Too young to drive")

The same logic is often cleaner with and:

if age >= 18 and has_licence:
    print("You can drive")

7. Combining Conditions

temp = 28
if temp > 20 and temp < 35:
    print("Pleasant weather")

# Python allows chained comparisons - more readable!
if 20 < temp < 35:
    print("Pleasant weather")

day = "Sunday"
if day == "Saturday" or day == "Sunday":
    print("Weekend!")

# shorter with "in"
if day in ("Saturday", "Sunday"):
    print("Weekend!")

8. Truthy and Falsy Conditions

A condition does not need a comparison. Python treats 0, "", [], {}, None and False as False; everything else is True.

name = input("Enter name: ")
if name:                      # True if not empty
    print("Hello,", name)
else:
    print("You didn't enter anything")

cart = []
if not cart:
    print("Your cart is empty")

9. One-line if (Ternary / Conditional Expression)

Syntax: value_if_true if condition else value_if_false

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

x = 7
print("Even" if x % 2 == 0 else "Odd")   # Odd

10. match-case (Python 3.10+)

When you compare one variable against many fixed values, match-case is cleaner than a long elif chain.

command = "stop"

match command:
    case "start":
        print("Starting...")
    case "stop":
        print("Stopping...")
    case "pause" | "wait":
        print("Pausing...")
    case _:
        print("Unknown command")   # _ is the default case
# Stopping...

11. pass — An Empty Block

Python does not allow an empty block. Use pass as a placeholder while you are still writing code.

if marks > 100:
    pass        # TODO: handle invalid marks later

12. Common Mistakes

MistakeProblemCorrect
if x = 5:SyntaxError — = is assignmentif x == 5:
if x > 5Missing colonif x > 5:
Body not indentedIndentationErrorIndent with 4 spaces
else if x > 5:SyntaxErrorelif x > 5:
if day == "Sat" or "Sun":Always True! "Sun" is truthyif day in ("Sat", "Sun"):
else x > 5:else takes no conditionelse:

13. Mini Project: Leap Year Checker

A year is a leap year if it is divisible by 4, except century years, which must be divisible by 400.

year = int(input("Enter a year: "))

if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
    print(year, "is a Leap Year")
else:
    print(year, "is NOT a Leap Year")

# 2024 -> Leap Year, 1900 -> NOT a Leap Year, 2000 -> Leap Year

Bonus: Simple Calculator

a = float(input("First number: "))
op = input("Operator (+, -, *, /): ")
b = float(input("Second number: "))

if op == "+":
    print(a + b)
elif op == "-":
    print(a - b)
elif op == "*":
    print(a * b)
elif op == "/":
    print(a / b if b != 0 else "Cannot divide by zero")
else:
    print("Invalid operator")

Quiz: Predict the Output

Don't run the code yet! Write your answers in a notebook, then check the Answers section at the end of this blog.

Q1. What is the output?

x = 5
if x > 3:
    print("A")
elif x > 1:
    print("B")
else:
    print("C")

Q2. What is the output?

if 0:
    print("yes")
else:
    print("no")

Q3. What is the output?

a = 5
if a > 2 and a < 4:
    print("in")
else:
    print("out")

Q4. What is the output?

x = 7
if x > 5:
    print("big")
if x > 6:
    print("bigger")

Q5. What is the output?

print(1 < 2 < 3, 3 > 2 > 2)

Q6. What is the output?

day = "Monday"
if day == "Saturday" or "Sunday":
    print("Weekend")
else:
    print("Weekday")

Q7. What is the output?

n = 15
print("Fizz" if n % 3 == 0 else "Buzz")

Q8. What happens?

x = 10
if x = 10:
    print("ten")

Practice Challenges

Solve these from easy to tricky:

  1. Check whether a number is positive, negative or zero.
  2. Find the largest of three numbers using if-elif-else.
  3. Check whether a character is a vowel or a consonant.
  4. Electricity bill: first 100 units at ₹5/unit, next 100 at ₹7/unit, above 200 at ₹10/unit. Calculate the bill.
  5. Classic FizzBuzz: for a number, print "FizzBuzz" if divisible by 3 and 5, "Fizz" if by 3, "Buzz" if by 5, else the number.
  6. Check whether a triangle with sides a, b, c is valid, and whether it is equilateral, isosceles or scalene.

Solutions for challenges 2, 4 and 5 are in the Answers section.

Self-Check: Can You Do This?

Tick off each skill once you are confident:

Frequently Asked Interview Questions

Q: What is the difference between if-elif and multiple if statements?
In an if-elif chain, only the first True branch runs. With separate ifs, every condition is checked and every True block runs.

Q: Does Python have a switch statement?
Python 3.10 introduced match-case (structural pattern matching). Before that, if-elif chains or dictionaries were used.

Q: What is short-circuit evaluation?
With and, Python stops at the first False; with or, at the first True. E.g. x != 0 and 10 / x > 1 never divides by zero.

Q: What is the ternary operator in Python?
a if condition else b — a one-line if-else expression.

Q: What is the use of pass?
It is a null statement used as a placeholder where a block is syntactically required.

Summary

  • if runs a block only when a condition is True; else handles the False case.
  • elif checks more conditions — only the first True branch runs.
  • Conditions use comparison (== != > < >= <=) and logical (and or not) operators.
  • Every block needs a colon and indentation.
  • Use chained comparisons, in, the ternary operator and match-case for cleaner code.

Quick Revision Cheat Sheet

ConceptSyntax / Key point
ifif x > 0:
if-elseif ...: ... else: ...
elifelif x == 0:
Ternary"Yes" if ok else "No"
Range checkif 1 <= x <= 10:
Membershipif x in [1, 2, 3]:
Pattern matchmatch x: case 1: ...

Answers

Quiz answers

  1. A – only the first True branch runs.
  2. no – 0 is falsy.
  3. out
  4. big and bigger – two separate if statements, both run.
  5. True False – 2 > 2 is False.
  6. Weekend – the bug! "Sunday" alone is truthy.
  7. Fizz
  8. SyntaxError – use == for comparison.

Challenge solutions

# Challenge 2
a, b, c = 12, 45, 30
if a >= b and a >= c:
    print("Largest:", a)
elif b >= c:
    print("Largest:", b)
else:
    print("Largest:", c)          # Largest: 45

# Challenge 4
units = 250
if units <= 100:
    bill = units * 5
elif units <= 200:
    bill = 100 * 5 + (units - 100) * 7
else:
    bill = 100 * 5 + 100 * 7 + (units - 200) * 10
print("Bill: Rs", bill)           # Bill: Rs 1700

# Challenge 5
n = 15
if n % 3 == 0 and n % 5 == 0:
    print("FizzBuzz")
elif n % 3 == 0:
    print("Fizz")
elif n % 5 == 0:
    print("Buzz")
else:
    print(n)                      # FizzBuzz

Conclusion

Your programs can now think and decide. Next, learn for and while loops so your programs can repeat tasks automatically.

If this blog helped you, watch the full video above, subscribe to the channel and share it with a friend who is learning Python. Happy coding!