Conditional programming (if statements) in Python

Coding with Python

🕑 This lesson will take about 30 minutes

In this lesson, you will learn how to use if statements in Python. An if statement is a control structure (a block of code that determines the flow of execution in a program) that allows the program to execute a block of code conditionally based on a specified condition. if statements provide a way for the program to make decisions based on the outcome of testing certain conditions. In other words, if a certain condition is true, the program will execute one set of instructions; and if the condition is false, the program will execute another set of instructions (or skip certain blocks of code).

Here are some examples of scenarios where if statements might be used in a program:

  • Checking if a player has passed a high score in a game

  • Checking if a user’s password is too short or too long when creating an account

  • Checking a user’s selection from different available options

if statements have two parts:

  • The condition that is being checked (which can either evaluate to True or False - this is known as a Boolean expression)

  • The instructions that will be carried out if the specified condition evaluates to True

if statements can also have optional elif (short for “else if”) that specify other conditions to check if the first condition is False, and else statements that can specify other code to run if none of the conditions are True. It is important to note that when using elif, you must specify a condition to test. However, when using else, you do not specify a condition (as the else block of code is only used when all other conditions to test have been covered).

The syntax and structure of an if statement looks like this:

if condition:

# Code that should run if the condition is true

elif another_condition:

# Code that should run if the first condition is False and this condition is True

else:

# Code that should run if none of the above conditions are True

Different ways that an if statement can be written include:

  • An if statement could contain a single if expression with a specified block of code to run if that condition is True

  • An if statement could have an if with one elif, or an if with one or many elif expressions, or an if with one or many elif conditions and/or one else statement

  • There can be one or many elif statements with a related if statement, but there can only ever be one else with a related if statement

  • An elif or else cannot be on its own (there must be an if first, before any elif or else statements can be added)

  • You must ensure that the code you wish to run (if the condition evaluates to true) is indented (tab-spaced).

  • The order of if and elif conditions is important. The code associated with the first condition that evaluates to True will run, and the program will ignore all the other conditions after this and return control back to the code the comes after the if/elif/else block.

Relational operators

Relational operators are used to make comparisons between things and check if different conditions are true, for example, to check if two strings are the same (equal), or check if one number is equal to, greater than, or less than another.

Relational operators that you can use in Python include:

  • Equal to ==

  • Not equal to !=

  • Greater than >

  • Less than <

  • Greater than or equal to >=

  • Less than or equal to <=

Let’s check out some different examples of if statements in Python code using a range of relational operators…

Example of an if statement

In the example below, the input() function has been used to ask the user to enter 'yes' or 'no' and then store their selection in the variable called choice. A single if statement is used to check if the user entered 'yes', and if so, then display a message.

  • Note that any code that is indented immediately after the if expression (after the : colon character) will run if the condition evaluates to false.

  • Any code after the if expression that is not indented is not part of the if statement’s code block. So, for example, the print("Goodbye") line of code will always run, regardless of whether the user selects 'yes' or 'no'.

  • Notice that there is no elif or else in this example. This means there is no specified code to run if the user enters 'no' (or any other value other than 'yes' for that matter).

Example of an if statement with elif

Here is some example code where elif has been used. If the user enters 'yes', then one block of code will run, and if the user enters 'no', then another block of code will run instead.

Example of an if statement with elif and else

Here is an example of where both elif and else have been used with an if statement. In this example, if the user enters 'yes', then one block of code will run, if the user enters 'no', then another block of code will run instead, and if the user enters input that is neither 'yes' or 'no', then another completely different block of code will run.

Logical operators

Logical operators can be used to combine different conditions in one statement.

  • and - checks if all specified conditions in an expression are True

  • of - checks if at least one of the specified conditions in an expression is Tru

For example, let’s say we want to check if a user’s password is between 10 and 40 characters in length (in other words, greater than or equal to 10 characters AND less than or equal to 40 characters in length). We could write code like this:

In the example below, the program checks if is the weekend. To do this, it checks whether the day is a saturday OR a sunday.

Example 1 - checking a score in a game

The code below displays different messages depending on which range a player’s score falls into. Note that there’s no else block in this example as all cases have been covered.

Example 2 - guessing a random number

In this example, the user needs to guess a secret random number (they only get one attempt). The program will check if the user’s attempt is correct, or if their attempt was higher or lower than the random number. Notice that the random module is imported to generate a random integer between 1 and 10, and the user’s input must be converted to an integer before it can be compared to other integer values.

Example 3 - working with Booleans

In this example, a program checks whether the value of a Boolean variable (game_over) is set to True or False. This could be written, for example, as game_over == True: but can also be shortened to if game_over: like in the example below. If we wanted to check if game_over = False: we could also use the not operator and write if not game_over: .

Checking membership in an object (such as a string or list)

If statements can also be used to check membership in an object such as a string or a list (in other words, check if a value exists in a list or if a character exists in a string) using the in operator. Note: You can also write not in if you want to check if something does not exist in an object. Check out the examples below.

Next lesson: While loops