Python If-Else

Decision-making is a crucial aspect of programming. It allows us to execute specific blocks of code based on certain conditions. In Python, decision-making is implemented using various statements that evaluate conditions and determine the flow of the program based on whether the condition is true or false. These statements help in making decisions in the code and control the flow accordingly.

Here are the key decision-making statements in Python:

Statement Description
if Executes a block of code if the specified condition is true.
else Executes a block of code if the condition in the if statement is false.
elif Checks another condition if the previous if or elif condition is false.
nested if You can have an if statement inside another if statement.
if-else Ladder Multiple if statements can be chained together with elif for multiple conditions.

1. if Statement

The if statement is used to test a specific condition. If the condition is true, the code block within the if statement is executed.

Example:

x = 10

if x > 5:
    print("x is greater than 5")

Output:

x is greater than 5

In this example, the condition x > 5 is true, so the message "x is greater than 5" is printed.

2. else Statement

The else statement follows an if statement and is executed when the condition in the if statement is false.

Example:

x = 3

if x > 5:
    print("x is greater than 5")

else:
    print("x is not greater than 5")

Output:

x is not greater than 5

Here, since x > 5 is false, the else block is executed, printing "x is not greater than 5".

3. elif Statement

The elif statement allows for multiple conditions to be tested sequentially. It stands for "else if."

Example:

x = 5

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")

Output:

x is equal to 5

In this example, the first condition x > 5 is false, so the program checks the next condition x == 5, which is true, and prints "x is equal to 5".

4. Nested if Statement

A nested if statement is an if statement inside another if statement. It allows for more complex decision-making.

Example:

x = 10

y = 20

if x > 5:
    if y > 15:
        print("x is greater than 5 and y is greater than 15")

Output:

x is greater than 5 and y is greater than 15

In this example, both conditions x > 5 and y > 15 are true, so the nested if statement's code block is executed.

5. if-else Ladder

An if-else ladder is a chain of if statements followed by elif and an optional else at the end.

Example:

x = 10

if x > 20:
    print("x is greater than 20")

elif x > 10:
    print("x is greater than 10")

elif x > 5:
    print("x is greater than 5")

else:
    print("x is 5 or less")

Output:

x is greater than 5