Control Flow

If-else statements, loops (for, while), break/continue

5 free lessons available

Start here

If-Elif-Else Statements

How do you ensure your program makes the right choices, every time, without becoming a tangled mess of logic? The answer lies in conditional statements, which allow your code to execute different blocks of instructions based on whether certain conditions are met. This capability is essential for creating dynamic and responsive applications that can adapt to various inputs and scenarios.

Without conditional logic, programs would follow a single, predetermined path, severely limiting their utility. By introducing decision points, you empower your code to react intelligently, making it far more versatile. This lesson explores how if, elif, and else statements provide this crucial control over program flow.

The Basic 'If' Statement

The if statement is the simplest form of conditional execution. It allows a block of code to run only if a specified condition evaluates to True. If the condition is False, the code block associated with the if statement is skipped entirely, and the program continues execution from the line immediately following the if block.

This structure provides a fundamental way to introduce decision-making into your programs. It acts like a gatekeeper, permitting certain actions only when specific criteria are satisfied. Understanding this basic mechanism is the first step toward building more complex logical flows.

pythonChecking if a Number is Positive

Crafting Conditions with Boolean Logic

Boolean Expression
A statement that evaluates to either True or False. These expressions form the conditions within if, elif, and else statements.
Example: The expression age >= 18 is a boolean expression. If age is 20, it evaluates to True. If age is 16, it evaluates to False. Common comparison operators include ==== (equal to), !=!= (not equal to), >> (greater than), << (less than), >=>= (greater than or equal to), and <=<= (less than or equal to).

Adding an 'Else' for Alternatives

While an if statement handles a single condition, the else statement provides an alternative path when the if condition is False. This ensures that one of two distinct code blocks will always execute, covering both possibilities of a binary decision.

The else block does not have a condition of its own; it simply acts as the default path. If the if condition is true, the if block runs. If the if condition is false, the else block runs. This structure is ideal for situations where you need to perform one action if a condition is met, and a different action if it is not.

Handling Multiple Choices with 'Elif'

When you need to evaluate more than two mutually exclusive conditions, the elif (short for 'else if') statement comes into play. It allows you to chain multiple conditions together, creating a sequence of checks. The program evaluates each elif condition in order, from top to bottom.

As soon as an elif condition evaluates to True, its corresponding code block executes, and the rest of the elif and else chain is skipped. If none of the if or elif conditions are met, the final else block (if present) will execute. This structure ensures that only one block of code runs within the entire if-elif-else construct, providing a clear and efficient way to manage multiple decision paths.

Flow of an If-Elif-Else Statement
Loading diagram...
This flowchart shows how an 'if-elif-else' statement evaluates conditions sequentially, executing the first true block and then exiting the conditional structure.
pythonAssigning Grades Based on Score
Try It Yourself
Modify the grade assignment code to include a new grade, 'A+', for scores 95 and above. Ensure the logic correctly assigns 'A+' for scores like 97, and 'A' for scores like 92.
python

When Order Matters: Condition Priority

The order of conditions in an if-elif-else chain is critically important because conditions are evaluated sequentially. Once a condition evaluates to True, its corresponding block executes, and the rest of the chain is skipped. This means a broadly defined condition placed too early can inadvertently capture cases that a more specific condition was intended to handle.

For example, if you check for score >= 60 before checking for score >= 90, a score of 95 would incorrectly be assigned a 'D' because the score >= 60 condition would be met first. Always arrange your conditions from most specific to most general, or from highest threshold to lowest, to ensure the correct logic is applied.

Check Your Understanding
Given the following code, what will be printed if temperature is 25?

Real-World Use: Data Validation

pythonValidating User Age Input
Try It Yourself
Extend the validate_age function to also check if the age is an integer. If it's a float (e.g., 30.5), return "Warning: Age should be a whole number.". This check should occur after ensuring it's a number but before checking for negative or excessively high values.
python
Key Takeaways
  • if statements execute a code block only if a condition is True.

  • else statements provide a default path, executing their block if the preceding if condition is False.

  • elif statements allow for chaining multiple conditions, evaluated sequentially. Only the first True condition's block executes.

  • Conditions are built using boolean expressions and comparison operators (e.g., ====, >>, <=<=) that resolve to True or False.

  • The order of elif conditions is critical; place more specific or higher-priority conditions before more general ones.

  • Conditional statements are fundamental for data validation, ensuring inputs meet specific criteria and preventing errors.

  • By mastering if-elif-else, you gain precise control over program flow, enabling your code to make intelligent, adaptive decisions based on varying circumstances.

Open this lesson on its own page →

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