Python: if else Statement

The if else statement in Python is used to execute a block of code based on a condition. It allows you to perform different actions depending on whether a specific condition is true or false.

  • If statement
  • If else statement

The ” if ” statement is used to execute a block of code if a condition is true. On the other hand, the ” if else ” statement is used to execute one block of code if the condition is true, and another block means the else statement if the condition is false. This allows for different actions to be taken depending on the result of the condition.

Remember to pay attention to indentation while writing these statements. Proper indentation ensures that the correct code blocks are associated with each condition.

Syntax

x = 10
if x > 5:
    print("x is greater than 5")
else:
    print("x is less than or equal to 5")

In this example, if the condition ” x > 5 ” is true, the code inside the ” if ” block is executed. Otherwise, the code inside the ” else ” block is executed. This is a fundamental concept in programming and is used extensively to control the flow of a program based on different conditions.