python
  1. python-if-else-statements

Python If-Else Statements

If-Else statement is used to execute a certain block of code only when a certain condition is met. The If-Else statement in Python helps in decision-making.

Syntax:

The syntax of the If-Else statement in Python is as follows:

if condition:
    # block of code to be executed if condition is True
else:
    # block of code to be executed if condition is False

Example:

# Program to check if a number is even or odd
num = int(input("Enter a number: "))

if num % 2 == 0:
    print(num, "is even.")
else:
    print(num, "is odd.")

Output:

Enter a number: 12
12 is even.

Explanation:

In this example, we have taken the input from the user and checked whether the number entered is even or odd using the If-Else statement.

If the number entered by the user is divisible by 2, then it is even; else, it is odd. Based on this condition, we have printed the output on the screen.

Use:

The If-Else statement is used in various applications such as:

  • Decision-making
  • Validating user inputs
  • Error handling
  • Data filtering
  • Data analysis
  • Control flow statements

Important Points:

  • An If-Else statement can have multiple Conditions.
  • The Else block is not mandatory.
  • An If-Else statement executes only when the condition is True.

Summary:

The If-Else statement in Python is used to execute a certain block of code when a certain condition is met. It helps in decision-making and is widely used in various aspects of programming. Understanding the If-Else statement is important to become a better Python programmer.

Published on: