The IF-ELIF-ELSE Statement

tags: #python/documentation/python_conditionals

What is a Multi-way Conditional Statement?

The if-elif-else statement allows you to specify multiple conditions and corresponding blocks of code to be executed based on the first true condition encountered. If none of the conditions is true, the block inside the else statement (if present) is executed.

Basic Syntax

if condition1:
    # Code to be executed if condition1 is True
elif condition2:
    # Code to be executed if condition2 is True
elif condition3:
    # Code to be executed if condition3 is True
    # ... (additional elif blocks)
else:
    # Code to be executed if all conditions are False
First True is Executed!

In a if-elif-else statement in Python, only the block associated with the first true condition is executed. Once a condition is true and its corresponding block is executed, the rest of the conditions (if any) are not evaluated.

Flow of Execution

Pasted image 20240110014613.png

Summary

  1. Each condition is checked in sequential order in which they are written.
  2. If one of them is True, the corresponding block of code is executed and the statement ends.
  3. If more than 1 condition is True, only the first True corresponding block of code is executed.

Powered by Forestry.md