Placement Prep

Python Conditionals: if, if-else, elif, and Nested if Explained

Python's if, if-else, elif, and nested if statements control program flow. Syntax, worked examples, and truthiness edge cases for 0, '', [], and None.

By FACE Prep Team 6 min read
python conditional-statements if-else elif placement-prep python-programs coding-practice

Python’s four conditional forms (if, if-else, elif, and nested if) control which blocks of code run based on whether conditions evaluate to True or False.

The Python Tutorial’s control flow section introduces all four in sequence. This article covers each form with syntax, a worked example, when to use it, and the edge cases that cost students marks in placement coding rounds.

The if statement

The if statement is the simplest conditional form. It executes an indented block when its condition is True and skips the block entirely when the condition is False.

Syntax

if condition:
    # block runs only when condition is True

Worked example

num = 8
if num > 0:
    print("num is positive")

Walking through the execution:

  • num > 0 evaluates to True (8 is greater than 0).
  • Python enters the indented block and prints num is positive.

Now change num to -3. The condition num > 0 is False. Python skips the block entirely. No output, no error. The program continues with whatever comes after the if statement.

When to use

Use a plain if when only the True path matters. If nothing needs to happen when the condition is False, there is no reason to add an else.

Edge case: if num > 0: versus if num:

These two conditions behave differently. if num > 0: is True only for strictly positive numbers. if num: is True for every non-zero value, including negative numbers. For the input -5, if num > 0: is False but if num: is True. Write the version that matches your intent precisely.

The if-else statement

Add an else clause to handle both outcomes: the True path and the False path.

Syntax

if condition:
    # block for True
else:
    # block for False

Worked example

num = 7
if num % 2 == 0:
    print("even")
else:
    print("odd")

Walking through the execution:

  • 7 % 2 equals 1, which is not equal to 0.
  • The if condition is False. Python jumps to the else block.
  • Output: odd

The even/odd check is one of the most common warm-up problems in AMCAT basic programming rounds. Getting the modulo condition right (num % 2 == 0 for even, not num % 2 == 1) is where many first attempts go wrong. Using num % 2 == 1 fails for negative numbers on most Python implementations, because Python’s modulo returns a non-negative result when the divisor is positive.

The Armstrong number check follows the same pattern. It computes a property of the input, compares it to the original value, and branches on whether they match.

One-liner ternary form

For simple two-branch decisions where both outcomes fit on one line, Python provides a ternary expression:

label = "even" if num % 2 == 0 else "odd"

This is readable when both branches are short. If either branch requires more than one operation, use the full if-else block instead.

The elif statement

elif (else-if) chains multiple mutually exclusive conditions. Python evaluates them in order and executes the first block whose condition is True. Once a match fires, all remaining elif and else blocks are skipped.

Syntax

if condition1:
    # block for condition1
elif condition2:
    # block for condition2
elif condition3:
    # block for condition3
else:
    # block when none of the above are True

Worked example: grade classification

score = 78
if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
elif score >= 60:
    grade = "C"
else:
    grade = "F"
print(grade)

Walking through the execution:

  • 78 >= 90 is False — skip.
  • 78 >= 75 is True — grade = "B". Python skips the remaining elif and the else block.
  • Output: B

Ordering matters

Write the most restrictive condition first. If the elif for >= 75 appeared before the if for >= 90, a score of 92 would match >= 75 first and incorrectly receive a B. Python checks conditions in the order they appear in the code, and stops at the first match.

Real placement applications

The calculator program in Python is a direct elif application: each arithmetic operation is one elif branch, and only one can match any given input. The greatest of three numbers program uses the same elif structure with >= comparisons across three values.

The character type classification article shows another standard elif pattern: classifying a character as uppercase, lowercase, digit, or special using four mutually exclusive branches.

Nested if statements

A nested if is an if statement written inside the block of another if (or elif or else). The inner condition is only evaluated if the outer condition is True.

Syntax

if condition1:
    if condition2:
        # inner True block
    else:
        # inner False block
else:
    # outer False block

Worked example: sign check

num = -5
if num != 0:
    if num > 0:
        print("positive")
    else:
        print("negative")
else:
    print("zero")

Three test cases to trace:

  • num = -5: outer num != 0 is True (enter outer block). Inner num > 0 is False (enter inner else). Output: negative.
  • num = 7: outer num != 0 is True. Inner num > 0 is True. Output: positive.
  • num = 0: outer num != 0 is False. Python skips the entire outer block. Output: zero.

Keeping nesting shallow

Two levels of nesting is the practical maximum before code becomes difficult to follow. Three-level nesting is a signal to refactor. The sign check above can be flattened into an elif chain:

if num > 0:
    print("positive")
elif num < 0:
    print("negative")
else:
    print("zero")

Both produce identical output. The flattened form is easier to read and test. Nested ifs are appropriate when the inner check genuinely only makes sense after the outer check passes, not just because the conditions happen to be related.

Combining conditions with and, or, and not

Python’s logical operators let you combine multiple conditions in a single if statement, which often removes the need for a nested if entirely.

# Instead of nesting:
if a > 0:
    if b > 0:
        print("both positive")

# Use and:
if a > 0 and b > 0:
    print("both positive")

Three operators:

  • and — True only if both sides are True.
  • or — True if at least one side is True.
  • not — inverts the boolean value.

Short-circuit evaluation applies. For A and B, if A is False, Python never evaluates B. For A or B, if A is True, Python never evaluates B. This matters when the second operand calls a function or could raise an error on certain inputs.

Python truthiness: what evaluates to True and False

Python does not require a strict boolean in a condition. Any expression can be used, and Python evaluates it as True or False based on Python’s truth value testing rules.

Falsy values

ValueTypeEvaluates to
0intFalse
0.0floatFalse
''stringFalse
[]listFalse
()tupleFalse
{}dictFalse
NoneNoneTypeFalse

Everything else evaluates to True, including the string '0' (non-empty), a list with one element, and the integer -1.

Practical implications

name = ""
if name:
    print("Hello,", name)
else:
    print("No name provided")

name is an empty string, which is falsy. The else branch fires. Output: No name provided.

items = []
if items:
    print("Processing", len(items), "items")
else:
    print("List is empty")

items is an empty list, which is falsy. Output: List is empty.

The if items: guard is idiomatic Python for checking whether a list has any elements, without writing if len(items) > 0:. Both produce the same result. The shorter form is standard in Python codebases.

The None trap

None is falsy, but so is 0. They are not the same thing. If you need to distinguish “the value is zero” from “no value was provided”, use if x is None: rather than if not x:. The latter conflates zero and None, which causes silent bugs when the zero case is meaningful.

The if-elif chain in the grade-classification example above checks four conditions in sequence. That same pattern governs how programs decide what to do based on a model output, a status code, or a classification result. TinkerLLM builds on Python conditionals like these to create programs that interact with LLM APIs, starting from ₹499.

Primary sources

Frequently asked questions

What is the difference between elif and else in Python?

elif attaches a new testable condition. Python checks it only if the preceding if or elif was False. else is a catch-all with no condition; it runs when everything above it has been False. You can chain as many elif blocks as you need between if and else.

Do I always need an else clause with an if statement?

No. An if statement without else is valid Python. If the condition is False, Python skips the if block and continues with the next statement. Add else only when you have code that must run on the False path.

What values are considered False in Python?

Python treats 0, 0.0, empty string '', empty list [], empty tuple (), empty dict {}, and None as False. Any object whose __bool__() method returns False is also falsy. Everything else is treated as True, including the string '0' and a list containing a single element.

How deep can I nest if statements in Python?

Python has no hard nesting limit, but beyond two levels the logic becomes difficult to read and test. If you find yourself at three or more levels, restructure the code using combined conditions with 'and' or 'or', or use early returns inside a function.

What is Python's ternary operator?

It is a one-line conditional expression: result = value_if_true if condition else value_if_false. For example, label = 'even' if num % 2 == 0 else 'odd' assigns the correct label in a single statement without a full if-else block.

Can I chain multiple elif blocks after an if?

Yes. You can write as many elif blocks as the problem requires between the opening if and the optional else. Python evaluates them in order and executes the first one whose condition is True, skipping all remaining elif and else blocks.

Why does 'if x:' work for lists and strings in Python?

Python calls the __bool__() method on the object (or __len__() if __bool__ is absent). An empty list has length 0 and evaluates to False. A non-empty list has a positive length and evaluates to True. The same applies to strings, tuples, dicts, and sets.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹499)
Free AI Roadmap PDF