Python Programming

IF Statements

IF statements are branching statements used for conditional execution of a program in the Python programming language.

IF statements execute when a programmer defined condition is true. The condition allows the IF statement to be used for decision making.

Decision making is required when we want to execute a piece of code if certain conditions are met.

IF Statement

IF Statement Flowchart

The standalone IF statement checks is a condition is true and executes the statements under it.

Standalone IF Statement

The above standalone IF statement makes no provision for when the condition is false.

IF statements can also be placed one after the other to execute in sequence as shown below:

Combined IF Statements

ELIF Statement

ELIF Statement Flowchart

ELIF allows you to chain multiple expressions for True and execute a block of code as soon as one of the conditions evaluates to true.

It is the equivalent of chaining IF statements in sequence. An example of this is show below:

Compound IF Statements

Note that the first IF statement is the IF statement that you are used to. The ELIF statements follows it.

ELSE Statement

ELSE Statement Flowchart

ELSE statements go with the IF statement. They are used for when the conditions that we are testing for fails.

The can be used with the standalone IF statement as shown below:

ELSE Statement

The ELSE statement can also be used with the compound IF statements as shown below:

Compound ELSE Statement

In the above program, we would only get to the ELSE block when the other conditions fail.