Python if else Statement

To write program almost all time you have to need the ability to check conditions. Python if else statement will give you the ability.


Python if Statement

The most common type of conditional statement is the if statement. If the statement's condition is true then the if statement's block will execute. The block will skip if the condition is false. In Python the if statement includes the following:

  • The if keyword
  • The condition part
  • A colon(:)
  • An indented block at the starting of next line

Example:

  1. x = 10
  2. y = 15
  3. if x<y:
  4. print("x is smaller than y.")

Output:

x is smaller than y.

Python elif Statement

Sometime you have to need to execute one of many possible clauses. The elif statement provides another condition that is check only when any previous condition were false. In Python the elif statement includes the following:

  • The elif keyword
  • The condition part
  • A colon(:)
  • An indented block at the starting of next line

Example:

  1. x = 10
  2. if x<0:
  3. print("x is negative.")
  4. elif x>0:
  5. print("x is positive.")

Output:

x is positive.

Python else Statement

The else statement is only executed when the condition of if statement is false. In Python the else statement includes the following:

  • The else keyword
  • A colon(:)
  • An indented block at the starting of next line

Example:

  1. x = 0
  2. if x<0:
  3. print("x is negative.")
  4. elif x>0:
  5. print("x is positive.")
  6. else:
  7. print("x is zero.")

Output:

x is zero.