Tutorials Logic, IN info@tutorialslogic.com

Python if elif else Statement Conditional Logic

Condition Basics

Conditional statements let Python choose one path based on a true or false result.

Use if for the first condition, elif for extra choices, and else for the fallback when nothing above matched.

Clear condition logic is about asking one question at a time and making each branch easy to read.

Python Conditions

Conditional statements let your program make decisions - executing different code based on whether a condition is True or False. Python uses if, elif, and else.

if Statement

Run a Block When a Condition Is True

Run a Block When a Condition Is True
age = 20

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

# Nothing happens if condition is False
temperature = 15
if temperature > 30:
    print("It's hot!")  # not printed

if else Statement

if-else

if-else
score = 75

if score >= 60:
    print("Pass")
else:
    print("Fail")

# Check even or odd
number = 17
if number % 2 == 0:
    print(f"{number} is even")
else:
    print(f"{number} is odd")   # 17 is odd

if elif else

Use elif (short for "else if") to check multiple conditions in sequence.

Grade Bands with if-elif-else

Grade Bands with if-elif-else
score = 82

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Grade: {grade}")  # Grade: B

# Multiple conditions with and/or
age = 25
income = 50000

if age >= 18 and income >= 30000:
    print("Loan approved")
elif age >= 18 or income >= 50000:
    print("Partial approval")
else:
    print("Not eligible")

Nested if Statements

Nested if

Nested if
num = 15

if num > 0:
    print("Positive")
    if num % 2 == 0:
        print("and even")
    else:
        print("and odd")   # Positive and odd
elif num < 0:
    print("Negative")
else:
    print("Zero")

Ternary Expression

A one-line shorthand for simple if-else. Syntax: value_if_true if condition else value_if_false

Choose a Value in One Line

Choose a Value in One Line
age = 20
status = "adult" if age >= 18 else "minor"
print(status)  # adult

# Equivalent to:
# if age >= 18:
#     status = "adult"
# else:
#     status = "minor"

# In a print statement
x = 42
print("positive" if x > 0 else "non-positive")  # positive

# Nested ternary (use sparingly - can hurt readability)
score = 75
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
print(grade)  # C

match Statement

Python's structural pattern matching - similar to switch/case in other languages but much more powerful.

Match a Command Value

Match a Command Value
command = "quit"

match command:
    case "quit":
        print("Quitting...")
    case "help":
        print("Showing help")
    case "start":
        print("Starting...")
    case _:           # default (wildcard)
        print(f"Unknown command: {command}")

# Match with conditions (guards)
point = (0, 5)
match point:
    case (0, 0):
        print("Origin")
    case (x, 0):
        print(f"On x-axis at {x}")
    case (0, y):
        print(f"On y-axis at {y}")   # On y-axis at 5
    case (x, y):
        print(f"Point at ({x}, {y})")

Truthy and Falsy Values

In Python, conditions don't have to be explicit True/False. Many values are considered truthy or falsy.

Falsy Values Truthy Values
False True
None Any non-zero number
0, 0.0, 0j Non-empty string
- (empty string) Non-empty list/tuple/set/dict
[], (), {}, set() Any object by default

Truthy/Falsy in Practice

Truthy/Falsy in Practice
name = ""
if name:
    print(f"Hello, {name}")
else:
    print("Name is empty")

items = []
if items:
    print("Has items")
else:
    print("Empty list")

result = None
if result is None:
    print("No result yet")

username = ""
display = username or "Guest"
print(display)
Output
Name is empty
Empty list
No result yet
Guest
Condition checkpoint

Can You Control Program Decisions?

5 checks
  • Conditional statements let your program make decisions - executing different code based on whether a condition is True or False.
  • An elif branch is evaluated only when every earlier condition in the chain was false.
  • A one-line shorthand for simple if-else.
  • Use match when fixed choices or patterns are clearer than a long elif chain.
  • In Python, conditions don't have to be explicit True/False.

Condition Decisions

0 of 2 checked

Q1. Why should specific conditions often come before broad conditions?

Q2. Which structure fits several exclusive score ranges?

Decision Logic Bugs

  • Checking broad rules before specific ones

    Put the most specific condition first so it is not swallowed by an earlier branch.
  • Repeating the same condition shape

    Simplify overlapping if and elif branches before adding more cases.
  • Relying on truthiness without clarity

    Use explicit checks when empty string, zero, None, and empty list mean different things.

Try this next

Write Decision Rules

0 of 2 completed

  1. Combine is_active and has_password into a readable decision.
  2. Create a discount rule where VIP customers are checked before normal customers.

Questions About Condition Logic

Use elif when only one branch should run. Use separate if statements when several independent checks may all run.

No. else is the fallback branch when the preceding if and elif conditions were false.

Use clear boolean names, avoid deeply nested branches, and split complex checks into smaller helper variables.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.