PythonConditional Statements and LoopsPython conditional statements

What are conditional statements in Python?

Question 49 of 88 · Updated

On this page

Conditional statements allow a Python program to choose which block of code to execute according to a condition. The main conditional statement is if, optionally followed by one or more elif clauses and a final else clause. Instead of running every instruction sequentially, a program can take different paths depending on its inputs or current state.

For example, an application might display a low-stock warning only when an item is nearly sold out. A grading program might select a grade according to a score.

1. The if statement#

PYTHON
temperature = 32 if temperature > 30: print('hot') print('done')

Output:

hot
done

Python evaluates the condition temperature > 30. Because the result is true, it executes the indented print statement. The final print statement is outside the conditional suite, so it executes after the conditional completes regardless of whether the condition is true, assuming no earlier exception or other control transfer interrupts execution.

A conditional statement consists of a header ending with a colon and a suite of statements. A multiline suite uses indentation to identify its boundaries. Four spaces per indentation level are the usual PEP 8 convention.

Loading diagram…

2. The if-else statement#

When exactly one of two alternative actions should execute, use if with else.

PYTHON
def parity(n): if n % 2 == 0: return 'even' else: return 'odd' print(parity(0), parity(-3))

Output:

even odd

The condition checks whether an integer is divisible by two. If it is, the function returns 'even'. Otherwise, the else suite returns 'odd'. This works for positive integers, zero and negative integers.

The else clause has no condition of its own. It is selected when the preceding condition or conditions in the same if statement are all false.

3. The if-elif-else statement#

Use elif, short for else if, when choosing among several alternatives.

PYTHON
def grade(score): if not 0 <= score <= 100: return 'invalid' elif score >= 90: return 'A' elif score >= 75: return 'B' elif score >= 60: return 'C' else: return 'D' print([grade(s) for s in (-1, 0, 59, 60, 74, 75, 89, 90, 100, 101)])

Output:

['invalid', 'D', 'D', 'C', 'C', 'B', 'B', 'A', 'A', 'invalid']

This example defines illustrative grading thresholds and assumes ordinary numeric scores. A real grading system should use its own approved rules and validate input types, including whether fractional scores and non-finite numbers are permitted.

Loading diagram…

Python evaluates these conditions in source order. The first truthy condition selects its suite; subsequent elif conditions are not evaluated. If no condition is truthy, the else suite is selected if one exists. If there is no else clause, execution simply continues after the statement.

Order matters. In the grading example, testing score >= 60 before score >= 90 would classify a score of 95 incorrectly because the earlier condition already matches.

4. if, elif and else compared#

KeywordPurposeCondition required?Number allowed in one chain
ifIntroduces the conditional statementYesExactly one
elifTests another alternative when earlier tests are falseYesZero or more
elseHandles the remaining casesNoZero or one, at the end

A single if-elif-else chain selects at most one suite. Separate if statements are independent decisions.

PYTHON
n = 12 if n % 2 == 0: print('even') if n % 3 == 0: print('multiple of three')

Output:

even
multiple of three

Both conditions are true, so both statements execute. Changing the second if to elif would make it an alternative to the first branch, and only 'even' would be printed.

Use independent if statements for independent actions, and use an elif chain for mutually exclusive alternatives.

5. When conditions are evaluated#

PYTHON
def check(name, value): print(name) return value if check('first', False): print('A') elif check('second', True): print('B') elif check('third', True): print('C')

Output:

first
second
B

The third check is not called because the second condition is true. This behavior matters when conditions involve function calls, expensive calculations or side effects.

Do not put work that must always occur inside a condition that might be skipped. Keep important effects explicit, and prefer predictable conditions over complicated expressions that mutate shared state.

If evaluating a condition raises an exception, ordinary if execution does not automatically move to the next elif or else. The exception propagates according to Python's exception-handling rules.

6. Conditions use truth-value testing#

An if condition does not have to be an expression of type bool. Python tests the truth value of the resulting object. Zero, None and empty built-in collections are normally falsy. Nonzero numbers and nonempty built-in collections are normally truthy. User-defined classes can customize truth testing.

The earlier Boolean lesson explains __bool__, __len__, operand-return semantics and short-circuit operations. For conditional statements, the key is to choose a test that expresses the actual requirement.

PYTHON
def available(stock): if stock is None: return 'unknown' if stock == 0: return 'sold out' return 'in stock' print(available(None), available(0), available(3))

Output:

unknown sold out in stock

None represents unknown stock, while zero represents a known empty inventory. A condition such as if not stock would combine these two states incorrectly. The example assumes stock is either None or a nonnegative integer; a production boundary should validate that contract.

Comparisons and logical operators make conditions expressive. Use the grouping rules from the preceding operator module, and add parentheses when mixing and with or would otherwise obscure the intended decision.

7. Nested conditional statements#

A conditional statement can contain another conditional statement in its suite.

PYTHON
def shipping(member, total): if member: if total >= 500: return 0 return 30 return 50 print(shipping(True, 500), shipping(True, 499), shipping(False, 500))

Output:

0 30 50

The inner condition is evaluated only when the outer membership condition is truthy. These illustrative rules use a free-shipping threshold of 500 for members, a fee of 30 for other member orders, and a fee of 50 for nonmembers. The amounts are examples, not actual commercial policies.

Loading diagram…

Indentation determines which else belongs to which if. Deep nesting can obscure these relationships. Keep nested conditions when they naturally represent dependent decisions, but consider extracting a helper or using guard clauses when the nesting grows.

8. Guard clauses and early returns#

The same shipping policy can be represented using flat conditions and early returns.

PYTHON
def fee(member, total): if member and total >= 500: return 0 if member: return 30 return 50 print(fee(True, 500), fee(True, 499), fee(False, 500))

Output:

0 30 50

For the intended Boolean member flag and numeric total, the function produces the same results as the nested version. The early return prevents the following statements from running once a result is selected.

Guard clauses are useful for rejecting invalid inputs, handling missing values and simplifying the main path. Do not mechanically rewrite nested conditions into repeated tests when those tests have side effects or expensive evaluation. A refactoring must preserve the intended semantics.

9. Conditional statements versus conditional expressions#

A conditional statement controls the execution of a suite. A conditional expression chooses one of two values.

PYTHON
def discount(qty): if qty < 0: raise ValueError('negative quantity') return 10 if qty >= 5 else 0 print(discount(4), discount(5))

Output:

0 10

The first if is a statement used to reject invalid input. The return line contains a conditional expression of the form value_if_true if condition else value_if_false. Python evaluates the condition first and only evaluates the selected value expression.

Use a conditional expression for a simple value choice. Use a statement for multiple actions, complicated conditions or cases where the expression would become difficult to understand. The example assumes a numeric quantity; a real quantity contract may require an integer type check and additional range validation.

10. Where match-case fits#

Python 3.10 introduced structural pattern matching through match and case. This is another decision-making construct, but it has distinct pattern semantics rather than being an ordinary sequence of Boolean if tests.

PYTHON
def route(action): match action: case 'start': return 'starting' case 'stop': return 'stopping' case _: return 'unknown' print(route('start'), route('pause'))

Output:

starting unknown

This introductory example matches literal actions. Structural pattern matching also supports destructuring, captures, guards and other patterns, which deserve a separate lesson. Prefer if for general Boolean predicates and use match where pattern structure expresses the decision naturally.

11. Conditional statements and variable scope#

Ordinary if blocks do not create a separate lexical scope. A name assigned within an if suite may be available after the statement, but only if the relevant execution path established the binding.

For example, assigning result only when a flag is true and returning result unconditionally can raise UnboundLocalError when that flag is false. Initialize a value on every relevant path, or return directly from each branch.

The earlier variable-scope lesson explains local binding classification and why Python cannot always fall back to a global value.

12. Complexity and branch coverage#

The time complexity of an if statement depends on the conditions actually evaluated and the suite selected. A chain of k conditions can evaluate up to k predicates before choosing a branch or determining that none matches.

If each predicate and selected suite has bounded cost, the worst-case cost of the chain is O(k), with constant auxiliary storage attributable to the decision structure itself. If a condition performs a linear search or a branch runs a large algorithm, account for those costs separately.

Test every reachable branch as well as threshold boundaries. The grading example tests invalid scores, exact thresholds, values immediately below thresholds and the maximum permitted score. This catches incorrect condition ordering and boundary mistakes such as using > instead of >=.

13. Common mistakes#

MistakeConsequence or correction
Missing colon after ifSyntaxError
Incorrect indentation after a multiline headerIndentationError
Writing if x = 1SyntaxError; use == for equality
Reading a local assigned only on an untaken branchPossible UnboundLocalError
Testing broad conditions before narrower conditionsAn earlier branch can prevent the intended later branch from running
Using several if statements instead of elif for alternativesMultiple actions may execute
Assuming else catches exceptionsIt handles unmatched conditions, not exceptions

Five independent failure tests confirmed SyntaxError for a missing colon, IndentationError for a missing indented suite, SyntaxError for ordinary assignment in a condition, UnboundLocalError for a local never initialized on the executed path, and ValueError for the negative-quantity validation example.

Frequently asked questions#

Is else mandatory in Python?#

No. An if statement can appear alone, with elif clauses, with else, or with both.

Can multiple elif branches execute in the same chain?#

No. Once a condition is truthy, Python selects that suite and skips the remaining alternatives in the chain.

Can an if condition contain a function call?#

Yes. Python evaluates the call and tests its result for truthiness. Later conditions may be skipped, and an exception raised during evaluation propagates normally.

What is the difference between if and elif?#

if starts a new conditional statement. elif belongs to an existing statement and is considered only when the preceding conditions in that chain are false.

Does indentation matter?#

Yes. Indentation determines the boundaries of multiline suites and their nesting relationships.

What is the difference between a conditional statement and a loop?#

A conditional statement selects a branch when reached. A loop repeats execution according to an iteration or continuation rule. The two constructs can be combined.

Interview-ready answer#

Conditional statements in Python control which code executes based on truth-tested conditions. The if keyword starts a decision, elif provides additional alternatives, and else handles the case where no earlier condition matches. A single chain executes at most one suite, while independent if statements may each execute. Python evaluates conditions in source order and skips later alternatives after the first truthy condition. Indentation defines suites and nesting. Use clear predicates, correctly ordered boundaries, explicit absence checks and branch tests to make conditional logic predictable.

Official references#

Verification note: Ten runnable examples were executed independently on CPython 3.13.5 and matched their documented output. Five expected-exception tests passed. The three fenced Mermaid flowcharts were manually reviewed for branch structure and labels. The Mermaid package and CLI were unavailable locally, so parser validation and public-site rendering were not performed. Official references are provided under the authorized offline research exception; live documentation and Supabase changelog were not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design