if-elif python
Conditional Statements in Python
In real-life scenarios, we often make decisions based on certain conditions. The same concept applies to programming—sometimes we want certain parts of the code to execute only if specific conditions are met. In Python, we use conditional statements to control this flow.
Python provides the following conditional statements:
-
if -
if...else -
nested if -
if...elif...else
Let’s explore each of them:
1. if Statement
The if statement allows you to execute a block of code only when a condition is True.
Syntax:
Example:
Output:
👀Note: In Python, indentation (whitespace) is used to define blocks of code.
2. if...else Statement
The if...else statement lets you execute one block of code if a condition is True, and another block if it is False.
Syntax:
Example 1:
Output:
Example 2 (Chained if...else):
Output:
3. Nested if Statement
You can place an if statement inside another if statement. This is called a nested if statement and allows for checking multiple levels of conditions.
Syntax:
Example:
Output:
4. if...elif...else Statement
The if...elif...else statement is a cleaner way to write multiple conditions. It is an alternative to writing long chains of nested if...else statements.
Syntax:
Example:
Output:
Summary
- Use
ifto execute code when a condition is True. -
Use
if...elseto handle both True and False cases. -
Use nested
ifwhen you need to check multiple conditions in layers. -
Use
if...elif...elsewhen you have multiple mutually exclusive conditions.