DevHireLab
Tutorials
BootcampProblemsCode SimulatorAI InterviewSoonContact
DevHireLab
Tutorials
BootcampProblemsCode SimulatorAI InterviewSoonContact
Getting Started
01
What is Python and Why Learn It in 2026
02
Installing Python on Windows, Mac, and Linux
03
Setting up VS Code / PyCharm for Python
04
Understanding the Python Interpreter and REPL
05
Writing and Running Your First Python Program
06
Python Syntax and Indentation Rules
Variables and Data Types
01
Variables and Naming Conventions in Python
02
Numbers in Python (int, float, complex)
03
Strings and String Methods in Python
04
Booleans in Python
05
Type Conversion / Casting in Python
06
Understanding the None Type in Python
Operators
01
Arithmetic Operators in Python
02
Comparison Operators in Python
03
Logical Operators in Python
04
Assignment Operators in Python
05
Bitwise Operators in Python
06
Identity (is) and Membership (in) Operators
07
Walrus Operator (:=) in Python
Input, Output & Strings
01
input() and print() Functions in Python
02
f-strings and String Formatting in Python
03
String Slicing and Indexing in Python
04
Common String Methods (split, join, strip, replace)
05
Escape Characters in Python Strings
Control Flow
01
if, elif, else Statements in Python
02
Nested Conditionals in Python
03
for Loops in Python
04
while Loops in Python
05
break, continue, and pass Statements
06
Loop with else Clause in Python
07
match-case (Structural Pattern Matching)
Data Structures
01
Python Lists: Creation, Indexing, Slicing, Methods
02
Python Tuples and Immutability
03
Python Sets and Set Operations
04
Python Dictionaries: Keys, Values, and Methods
05
List Comprehensions in Python
06
Dictionary & Set Comprehensions in Python
07
Working with Nested Lists and Dictionaries
Functions
01
Defining and Calling Functions in Python
02
Function Arguments: Positional, Keyword, Default
03
*args and **kwargs in Python
04
Return Statements in Python Functions
05
Lambda Functions in Python
06
Recursion in Python
07
Variable Scope: Local, Global, Nonlocal
08
Docstrings and Function Annotations
Functional Programming Basics
01
map(), filter(), and reduce() in Python
02
Closures in Python Explained
03
Python Decorators: Basic to Advanced
04
Generators and yield in Python
Object-Oriented Programming (OOP)
01
Classes and Objects in Python
02
The init Constructor in Python
03
Instance vs Class Variables in Python
04
Inheritance in Python (Single, Multiple, Multilevel)
05
Polymorphism in Python
06
Encapsulation in Python
07
Abstraction in Python with the abc Module
08
Magic/Dunder Methods in Python
09
Static and Class Methods in Python
10
The @property Decorator in Python
11
Python Dataclasses Explained
Error Handling
01
try, except, finally in Python
02
Handling Multiple Exceptions in Python
03
Raising Custom Exceptions in Python
04
Understanding Python's Exception Hierarchy
05
Assertions in Python
File Handling
01
Reading and Writing Text Files in Python
02
Working with the with Statement in Python
03
Working with CSV Files in Python
04
Working with JSON Files in Python
05
Working with Directories (os, pathlib) in Python
Modules and Packages
01
Importing Built-in Modules in Python
02
Creating Your Own Modules in Python
03
Understanding Packages and init.py
04
Python Standard Library Overview
05
Installing Packages with pip
Advanced Core Concepts
01
Iterators and Iterables in Python
02
Context Managers in Python (with, contextlib)
03
Multithreading Basics in Python
04
Multiprocessing Basics in Python
05
Asyncio Basics: async/await in Python
06
Memory Management and Garbage Collection in Python
07
Type Hints in Python (typing module)

if, elif, else Statements in Python

Every interesting program eventually needs to do different things depending on the situation — python if elif else statements are how that happens. Without conditional logic, code would only ever run the exact same way, top to bottom, no matter what input it receives. This article covers the three keywords that make branching logic possible, from a simple if up through nested conditions and the one-line shorthand version.

Introduction: Making Decisions in Code

A conditional statement lets your program execute different blocks of code depending on whether some condition evaluates to True or False. Without conditionals, every program would be a single straight line — the same instructions, in the same order, every single time, regardless of what data it's given.

Python gives you three keywords for this: if, elif (short for "else if"), and else. Together, they let you express logic like "do this if a condition holds, do something else if a different condition holds instead, and otherwise fall back to a default."

The Basic if Statement

Syntax
if condition:
    # indented block — runs only if condition is True

As covered in the earlier article on Python syntax and indentation, the colon and the indented block underneath aren't optional style — they're required syntax that defines where the conditional block starts and ends.

What happens when the condition is False

If the condition evaluates to False, Python simply skips the indented block entirely and moves on to whatever comes next in the program:

number = -5

if number > 0:
    print("The number is positive")

print("Done checking")

Since -5 > 0 is False, the print("The number is positive") line never runs — but the program doesn't stop or error out, it just continues past the block to the next line.

A simple example
number = 7

if number > 0:
    print("The number is positive")

Adding an Alternative with else

Two-way branching

An if on its own only handles the "True" case. Adding else gives you a second block that runs specifically when the condition is False — one or the other always runs, never both, never neither:

number = -3

if number > 0:
    print("The number is positive")
else:
    print("The number is not positive")
else needs no condition, and must come last

else doesn't take a condition of its own — it's the catch-all for "everything the if (and any elif blocks) didn't already handle." It also has to be the final block in the chain; there's no meaningful way to write anything after it in the same conditional structure.

Example: checking even vs. odd
number = 15

if number % 2 == 0:
    print("Even")
else:
    print("Odd")

Multiple Conditions with elif

What elif does

elif lets you check several conditions in sequence, one after another, stopping at the very first one that evaluates to True. Once a match is found, Python skips every remaining elif and else block entirely — even if a later condition would also have been True.

score = 85

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

print(grade)   # B
Order matters

This is genuinely important, and it's a common source of subtle bugs: because Python evaluates elif conditions top to bottom and stops at the first match, the order you write them in changes the outcome, especially with overlapping ranges.

score = 95

# Written correctly — most specific (highest) condition first
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
print(grade)   # A — correct
score = 95

# Written incorrectly — broader condition checked first
if score >= 80:
    grade = "B"
elif score >= 90:
    grade = "A"
print(grade)   # B — wrong! 95 satisfies score >= 80, so Python never even checks the second condition

The general rule: when your conditions overlap (as range checks like these do), order them from most specific to least specific — otherwise, a broader condition earlier in the chain can silently swallow cases that should have matched a more specific one further down.

Practical example: letter grades
def get_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

print(get_grade(72))   # C

Nested Conditionals and the Ternary Shorthand

Nested if statements

Sometimes a decision genuinely depends on more than one independent check, where the second check only makes sense after the first one has already passed. You can nest an if inside another if to express that:

age = 20
has_license = True

if age >= 18:
    if has_license:
        print("You can drive")
    else:
        print("You need a license first")
else:
    print("You're too young to drive")

Each level of nesting adds another indentation level, following the same rules covered in the earlier syntax article. As mentioned there too, it's worth keeping nesting shallow where you can — this two-level example is reasonable, but three or four levels deep starts getting hard to follow, and often signals the logic could be simplified (sometimes with and, as covered in the logical operators article: if age >= 18 and has_license:).

The ternary operator: one-line conditionals

Python supports a compact, single-line form of if/else, often called the ternary operator (or a conditional expression):

score = 75
status = "pass" if score >= 60 else "fail"
print(status)   # pass

The pattern reads almost like plain English: value_if_true if condition else value_if_false. This is genuinely useful for short, simple assignments where the full multi-line if/else block would feel like overkill:

age = 15
category = "adult" if age >= 18 else "minor"
When to use the ternary shorthand vs. full if/elif/else

The ternary form is best reserved for exactly the kind of case shown above: a simple, single condition, assigning one of two values, with no additional logic involved. Once you need more than two branches, or the condition itself is more than a single simple comparison, or there's any real logic beyond "pick one of two values," the full if/elif/else structure is almost always more readable:

# Fine as a ternary — simple, single condition
label = "even" if number % 2 == 0 else "odd"

# Not a good fit for ternary — too much branching logic to cram onto one line
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

Trying to force that grading logic into nested ternary expressions would technically work, but it would be far harder to read at a glance than the plain if/elif/else version — a good rule of thumb is: if you'd need to nest ternary expressions inside each other to express the logic, that's a strong signal to write it out as a full conditional block instead.

PREVIOUSNEXT LESSON