Conditional Statements (if/elif/else)

A user enters a password during login. How does your program decide if it's correct, too short, or needs a reset? This is where conditional statements come in, allowing your code to make decisions.

Making Decisions in Your Code

Programs often need to react differently based on various situations or inputs. Conditional statements provide the mechanism for this 'if this, then that' logic. They allow your code to execute specific blocks of instructions only when certain conditions are met.

Each condition you define evaluates to either True or False. If the condition is True, the associated code runs; otherwise, it is skipped. This fundamental ability to control program flow is essential for creating dynamic and responsive applications.

The Basic if Statement

The simplest form of conditional logic is the if statement. It checks a single condition and executes a block of code only if that condition is True. The syntax involves the if keyword, followed by the condition, and then a colon.

The code block to be executed is defined by indentation. In Python, all lines belonging to the if block must be indented consistently, typically by four spaces. If the condition evaluates to False, the indented code block is completely ignored, and the program continues execution from the line immediately following the if block.

pythonChecking a Single Condition

Building Conditions with Operators

Conditions are constructed using comparison operators to compare values and logical operators to combine multiple comparisons. Comparison operators determine relationships like equality or magnitude, while logical operators (and, or, not) allow you to create more complex decision criteria.

For instance, you might check if a number is both greater than 10 and less than 20. Understanding these operators is crucial for writing effective conditional logic.

📌 Common Comparison Operators
  • ==: Equal to
  • !=: Not equal to
  • <: Less than
  • >: Greater than
  • <=: Less than or equal to
  • >=: Greater than or equal to
pythonCombining Conditions with Logical Operators

The if-else Statement

While an if statement handles a single path, the if-else statement provides two mutually exclusive paths. If the if condition evaluates to True, its code block executes. However, if the if condition is False, the code block associated with the else keyword executes instead.

The else block acts as a default or fallback option, ensuring that one of two possible code paths is always taken. This structure is ideal for binary decisions, such as whether a user is logged in or not, or if a number is positive or negative.

pythonHandling Two Outcomes with `if-else`

The if-elif-else Statement

When you need to handle more than two possible outcomes, the if-elif-else structure is ideal. The elif keyword, short for 'else if', allows you to chain multiple conditions together. Python evaluates these conditions in order, from top to bottom.

As soon as an if or elif condition evaluates to True, its corresponding code block executes, and the rest of the elif and else blocks are skipped. If none of the if or elif conditions are True, the final else block (if present) serves as the ultimate fallback, executing its code. This ensures that exactly one block of code runs among all the possibilities.

pythonMulti-Path Decision Making
Flow of an `if-elif-else` Statement
Loading diagram...
This flowchart illustrates how an `if-elif-else` statement processes conditions sequentially. Only the code block for the first `True` condition executes, or the `else` block if all conditions are `False`.
Check Your Understanding
What will be the output of the following code snippet?

Indentation: Python's Block Structure

Unlike many other programming languages that use curly braces ({}) to define code blocks, Python relies entirely on indentation. The level of indentation determines which statements belong to which if, elif, or else block.

All statements at the same level of indentation are considered part of the same block. The standard practice in Python is to use four spaces for each level of indentation. Consistent indentation is not just a style choice; it is a fundamental part of Python's syntax, directly impacting how your program executes its control flow.

⚠️ Indentation Errors

Incorrect or inconsistent indentation will lead to an IndentationError. Mixing tabs and spaces, or using different numbers of spaces for the same block, can cause subtle bugs that are hard to trace. Always use a consistent indentation style, preferably 4 spaces.

Try It Yourself
Modify the password validation example to include an additional check: the password must not contain the username. Assume the username is 'user123'. Add an elif condition to check for this and print an appropriate message.
python
Key Takeaways
  • if statements execute code only when a specified condition is True.

  • Conditions are built using comparison operators (==, >, etc.) and can be combined with logical operators (and, or, not).

  • else provides a fallback path, executing its code block when the preceding if condition is False.

  • elif allows chaining multiple conditions; only the first True condition's block executes, and else is the final default.

  • Python uses 4-space indentation to define code blocks, which is crucial for correct control flow.

  • Conditional statements are how programs make dynamic decisions, such as validating user input like a password.

← All lessons in Python Basics & Syntax

Ready to keep this from fading?

Bitelrn turns lessons like this into a full course — quizzes, a knowledge map, and spaced review.

Get started free