In Python programming, we can use control statements like if, else, and elif to make decisions based on boolean values or expressions. Let’s explore how to use these statements effectively.

The if Statement

The if statement is used to execute a block of code when a condition is true. For example:

condition = True

if condition == True:
    # do something

Here, if the condition evaluates to True, the indented block of code below the if statement will be executed.

Blocks in Python

A block of code in Python is a set of statements that are indented at the same level. Typically, indentation is done with four spaces. For example:

condition = True

if condition == True:
    print("The condition")
    print("was true")

print("Outside of the if")

Here, both print statements are part of the block under the if statement. The block ends when the code indentation moves back to the previous level.

else and elif Statements

We can use the else statement to define an alternative block of code when the condition of the if statement is false. For example:

condition = True

if condition == True:
    print("The condition")
    print("was True")
else:
    print("The condition")
    print("was False")

In this case, if the condition is false, the block under the else statement will be executed.

We can also use multiple elif statements to perform additional checks. These statements are evaluated only if the previous condition was false. For example:

condition = True
name = "Roger"

if condition == True:
    print("The condition")
    print("was True")
elif name == "Roger":
    print("Hello Roger")
else:
    print("The condition")
    print("was False")

Here, if the condition is false, and the value of the name variable is “Roger”, the block under the elif statement will be executed.

Inline Format of if and else

In Python, we can use the inline format of if and else to return different values based on a condition. For example:

a = 2
result = 2 if a == 0 else 3
print(result)  # Output: 3

In this case, if the condition a == 0 is true, the value 2 will be assigned to the result variable. Otherwise, the value 3 will be assigned.

By using control statements like if, else, and elif, we can make decisions in our Python code effectively, resulting in more dynamic and versatile programs.