Conditional Statements

These types of statements can also be known as selection statements and are used to check if a particular condition is being met such as having to be 17 to be eligible to get your driving license. They will evaluate as False or True and then depending on the results specific code will be executed. Before we look at the statements we will look at Boolean Logic first.

Logical Operators

These are operations that are used to check logical conditions such as AND, OR, NOT.

AND requires that ALL of the outcomes are true for the condition to be true. OR just requires ONE of the conditions to be true. The easiest way to think about NOT is that it is the opposite of the condition.

Conditional Statements

Selection is the ability to do something if certain criteria is met, to do this in programming we will use conditional statements

We will use the IF.. THEN.. ELSE construct to allow pathways through program code.

A simple conditional statement.

A Simple Conditional Statement in Python

A simple conditional statement is one where there is only one condition to be met.

A complex conditional statement is when there is more than one condition to be tested.

Else and Else IF Statements

It will be required to perform an operation if the condition is true and a different set of code of the choice is False, such as in the flow chart below.

In Python this would look like below. The else: statement will be executed when any other if statements are false.

Python Example

The code above will ask the user to enter their username and password and then check if they are correct. It can be executed below.

ElseIf Statements

If statements are evaluated first but it is possible to use elif (Else if Statements) to check other conditions first before using an else statement that will only be executed if all others are False.

Python Example

The code above now uses an else if statement to check another set of conditions before using the else statement if nothing else has been true.

Python example demonstrating the use of if, elseif and else statements.

Conditional Statement - Tutorial Video

SDD 4 Conditional Statements.mp4