Control Flow: The if, elif, else Statements

The if and else Statements

Computers can be programmed to make decisions, rather than simply repeating a given process. For a decision to take place there has to be a set of parameters to be evaluated.

if (Condition):
    Process this section of the code if Condition is True

else:
    Process this section of the code if Condition is False

The else part is optional for the comparison and you do not have to include an else section if it is not required. However, the else statement has to be preceded by an if statement.

Try the following with inputs 2 and 11:

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

print("Value of x is", x)

if (x<10):
    print("x is less than 10")

if (x % 2 == 0):
    print("x is an even number")

else:
    print("x is an odd number")

Each if statement starts a conditional sequence that may be followed by zero or more elif conditional statements, and an optional else statement following the if and all of the elif statements if there are any. The Python indentation rules also apply to all conditional statements, in order to specify the boundaries of the code blocks.

There can be no code statements at the same indentation level between a single group of if-elif-else statements.

if (x % 2 == 0):
    print("x is an even number")

print("this print statement is indented at the same level as the \"if\" and the corresponding \"else\", so it breaks the link between the if and else, thereby causing an error.")

else:
    print("x is an odd number")