IF ELSE

conditional statements are used to make decisions in your code based on certain conditions. The primary conditional statements are if, elif (short for "else if"), and else. These statements are used to control the flow of a program based on whether a specific condition or set of conditions is true or false.

Here is the basic syntax for a simple if statement:

if condition:

    # Code to execute if the condition is true

You can extend the if statement using elif and else to handle additional cases:

if condition1:

    # Code to execute if condition1 is true

elif condition2:

    # Code to execute if condition2 is true

else:

    # Code to execute if none of the above conditions are true

Example: Checking if a number is positive, negative, or zero

number = int(input("Enter a number: "))

 

if number > 0:

    print("The number is positive.")

elif number < 0:

    print("The number is negative.")

else:

    print("The number is zero.")

In this example:

The if statement checks if the number is greater than 0.

The elif statement checks if the number is less than 0.

The else statement handles the case when none of the above conditions is true, i.e., the number is zero.

You can also use logical operators such as and, or, and not to combine multiple conditions in a single statement.

Example: Checking if a number is between 10 and 20

number = int(input("Enter a number: "))

 

if number >= 10 and number <= 20:

    print("The number is between 10 and 20.")

else:

    print("The number is not between 10 and 20.")