Skip to Content
TheCornerLabs Docs
DocsProgramming LanguageGrokking Python FundamentalsPython ConditionalsPython If...else

The if, elif, and else statements in Python are fundamental to controlling the flow of execution based on conditions. These statements allow you to execute specific blocks of code depending on whether certain conditions are true or false.

Below, we’ll break down how to use these constructs effectively across three sections, each focused on a different aspect of conditional execution.

The if Statement

The if statement is used to execute a block of code only if a specified condition is true.

Syntax

  • condition: This can be any expression that evaluates to True or False. If the condition is True, the code inside the block will execute.

Example

Explanation:

  • x = 10: Set the variable x to 10.
  • if x > 5: Check if x is greater than 5.
  • print(...): Since x is indeed greater than 5, the message “x is greater than 5” is printed to the console.

The else Statement

The else statement complements the if statement and specifies a block of code to be executed if the if condition is false.

1714011009775189 Image scaled to 50%

Syntax

  • The else block only executes when the if statement’s condition evaluates to False.

Example

Explanation:

  • x = 3: Set the variable x to 3.
  • if x > 5: Check if x is greater than 5.
  • else: Since x is not greater than 5, the else block executes.
  • print(...): Prints “x is not greater than 5”.

The elif Statement

The elif (else if) statement allows you to check multiple expressions for True and execute a block of code as soon as one of the conditions evaluates to True.

Syntax

  • elif allows for multiple conditions to be checked, each one after the previous one has evaluated to False.

Example

Explanation:

  • x = 15: Set the variable x to 15.
  • if x > 20: Check if x is greater than 20.
  • elif x > 10: Since x is not greater than 20 but is greater than 10, execute this block.
  • print(...): Prints “x is greater than 10 but not more than 20”.

This lesson provides a clear, step-by-step guide to using if, elif, and else statements in Python, covering their purposes, syntaxes, and practical examples with detailed explanations.

Last updated on