Conditional Statement in Python

Sat Jun 1, 2024

In Python, you can use conditional statements to execute different code blocks based on certain conditions. The primary conditional statements in Python are if, elif (short for "else if"), and else. Here's how they work:

if
statement:
The if statement is used to execute a block of code if a specified condition is True.

if condition:
# Code to be executed if the condition is True

elif statement:

The elif statement allows you to check multiple conditions one by one. It is used in conjunction with if and can follow one or more if blocks.


if condition1:
           # Code to be executed if condition1 is True elif
condition2:
          # Code to be executed if condition2 is True
else:
       # Code to be executed if neither condition1 nor condition2 is True

else statement:
The else statement is used to execute a block of code if the preceding conditions (if and elif) are False.

if condition:
        # Code to be executed if the condition is True
else:
      # Code to be executed if the condition is False

Example of a simple conditional statement:

x = 10

 if x > 5:

     print("x is greater than 5")

elif x == 5:

   print("x is equal to 5")

 else:

   print("x is less than 5")


In the above example, the code checks the value of x and prints different messages based on whether x is greater than 5, equal to 5, or less than 5.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Vijay Kashyap
Python