A Beginner's Guide to Conditional Statements in Python

Learn the Basics of Conditional Statements in Python

When it comes to decision making, we can have several choices which all lead to different outcomes. Selecting a particular choice could cause you to forgo the other options. For example, if I have two days to claim a ₦5000 prize there are different things I could do. I could claim the prize within two days, and decide to use that money to buy lots of candy or save that money to buy something else I really want. I could also forget to claim the prize before the two days are up, and lose access to that prize money. Here you can notice three different outcomes from three choices I could have made.

This can be translated to programming albeit in a slightly different manner (there might not be candy involved sadly) using conditional statements. When writing code, there could be a section of your code where you want certain things to happen based on some conditions that you will define, and these conditions cause branches in the code flow.

Conditional statements perform different actions depending on whether a specific condition is True or False. They are used to control the flow of execution of our program. Some statements are executed only if a condition is satisfied, and other statements are executed when the condition is not satisfied. The three conditional statements in python are:

  1. If statement
  2. If-else statement
  3. If-elif-else statement

These statements are made up of three reserved keywords in python – if, elif, and else. You can read up on the other reserved keywords in python here. In this tutorial we will learn about the conditional statements, see their syntax, and also see some examples of these statements.

If statement

This is a commonly used conditional statement which decides whether certain code should be executed based on whether it meets the specified condition. The if condition evaluates a Boolean expression, and the code body is executed only when the expression evaluates to True. The if statement has the following syntax:

if expression:
    Statement(s)

For example, let’s say you have the following code block:

number = 17
if number > 10:
    print("This number is greater than 10")

If we run this code, we are going to get the output:

This number is greater than 10

We get this output because the expression in our conditional statement evaluates to True, so the indented code block is executed i.e our number is greater than 10 (It is 17) so we are going to see our output in our terminal. What happens when we change the code a little bit?

number = 5
if number > 10:
    print("This number is greater than 10")

In this case, our output is going to be:

The condition evaluates to be False since 5 is not greater than 10, and the indented code block doesn’t run. Since we don’t have any other statements, our terminal is just going to be empty when we run this code.

You will notice some peculiarities in writing these conditional statements. The first thing is that the expressions are written using comparison operators. The comparison operators in python are:

  • equal to ( == )
  • not equal to ( != )
  • greater than ( > )
  • less than ( < )
  • greater than or equal to ( >= )
  • less than or equal to ( <= )

Depending on what you need to compare and evaluate, you use the appropriate comparison operators in your conditional expressions. For example, if I want to check whether a number is greater than or equal to a value in a variable I already defined and to print a string if it is:

stored_number = 16
if stored_number >= 10:
    print("The stored number is greater than or equal to 10")

You can find other examples of using comparison operators here.

Using a colon after your conditional statement is very important before you even start writing the indented code block. The code block you want to execute under the particular statement is indented by four (4) spaces. You should maintain the indent to write lines of code affected by the if/if-else/if-elif-else code blocks. When you are done, reduce the indent and go back to writing your code normally. These things are very important when writing conditional statements or else you will get errors when you run your code.

You can have multiple if statements, and each of them will have their own indented code block. For example:

number = 10

if number < 5:
    print("The number is less than 5")
if number % 2 == 0:
    print("The number is divisible by 2 without any remainder")
if number < 50:
    print("The number is less than 50")
if number == 13:
    print("The number is 13")

print("This code block is over")

The output is:

The number is divisible by 2 without any remainder

The number is less than 50

This code block is over

When this code block runs, any conditional statement that evaluates to True is executed and those that evaluate to False are skipped. At the end there is an additional print statement that runs because it is not a part of the indented code blocks.

If-else statement

This statement consists of an if code block and an else code block. The else block is used in conjunction with the if block, and it executes when the conditions in the if block evaluate to False. The else block doesn’t take expressions (conditions) as the if block does. The if-else statement has the following syntax:

if expression:
    Statement(s)
else:
    Statement(s)

Working with a previous example, we can have the following code block:

number = 17
if number > 10:
    print("This number is greater than 10")
else:
    print("This number is less than 10")

In this case when we run this code our else block isn’t going to run, and we are going to have the output:

This number is greater than 10

If we change the code a little bit and have this:

number = 5
if number > 10:
    print("This number is greater than 10")
else:
    print("This number is less than 10")

Our else block is going to run and we will have this output:

This number is less than 10

The else statement is an optional statement, and there could be at most only one else statement following an if statement.

In a case where you have multiple if statements and you want to add an else statement as well, the else statement will only evaluate if the if statement directly preceding it evaluates to False. If the other if conditions evaluate to False, it will have no effect on the else statement. For example:

if 10 > 15:  #condition one
    print("10 is greater than 15")
if 2 >= 1:  #condition two
    print("2 is greater than or equal to one")
if 45 == 45:  #condition three
    print("45 is the same as 45")
else:  #condition four
    print("This is an else statement")

When we run this code we will get the following output:

2 is greater than or equal to one

45 is the same as 45

Notice that although condition one evaluated to be False, the else block didn’t execute. This is because with multiple if statements the else block in this case will only execute if condition three evaluates to False. If we modify our code and we have:

if 10 > 15:  #condition one
    print("10 is greater than 15")
if 2 >= 1:  #condition two
    print("2 is greater than or equal to one")
if 45 == 100:  #condition three
    print("45 is the same as 100")
else:  #condition four
    print("This is an else statement")

Our output is going to be:

2 is greater than or equal to one

This is an else statement

We can see in this case that our else statement was executed when the preceding if statement (condition three) only evaluated to False, and other if statements evaluating to False (condition 1) had no effect on it.

If-elif-else statement

Elif stands for else if, and the code block cannot stand on its own so it is always chained to a precedence if block of code. The statement is used when we want only one branch of logic to ever execute. This means that if you have an if statement and multiple elif statements with an additional else block, once the if block evaluates to True none of the elif code blocks and the else code block will run.

In a case where the if statement evaluates to False, the multiple elif code blocks will be checked accordingly from top to bottom and only one of the elif code blocks will ever execute. If the if block evaluates to False and the multiple elif blocks also evaluate to False, then the else block will executed. Let’s look at some examples:

Example 1

guess_number = 30

if guess_number > 10:  #condition one
    print("The guess number is greater than 10")
elif guess_number > 20:  #condition two
    print("The guess number is greater than 20")
elif guess_number > 50:  #condition three
    print("The guess number is greater than 50")
else:  #condition four
    print("The guess number is less than 10")

The output is:

The guess number is greater than 10

Here you notice that when the if code block evaluated to True no other code block was executed even though the condition two also evaluates to True. This is the case with if-elif-else statements. Once one code block evaluates to be True and executes, no other code blocks after it execute even if they evaluate to be True.

Example 2

guess_number = 30

if guess_number < 10:  #condition one
    print("The guess number is less than 10")
elif guess_number > 20:  #condition two
    print("The guess number is greater than 20")
elif guess_number > 15:  #condition three
    print("The guess number is greater than 15")
elif guess_number > 50:  #condition four
    print("The guess number is greater than 50")
else:  #condition five
    print("The guess number is less than 10")

The output is:

The guess number is greater than 20

In this example, the if code block evaluated to False so the elif code blocks were examined in order by the python interpreter. Condition two was found to be True and executed accordingly and so condition three was not executed even if it was True.

Logically you would expect that you would check to see if the number is greater than 15 before going on to check whether it is greater than 20, but this is not how it was written in the code. Because the python interpreter interprets each line of code in the order it was written, you have to be careful when writing your code so you don’t run into situations like this. You could re-write the code to check if the number is greater than 15 first before going on to check whether it is greater than 20 as seen below:

guess_number = 30

if guess_number < 10:  #condition one
    print("The guess number is less than 10")
elif guess_number > 15:  #condition two
    print("The guess number is greater than 15")
elif guess_number > 20:  #condition three
    print("The guess number is greater than 20")
elif guess_number > 50:  #condition four
    print("The guess number is greater than 50")
else:  #condition five
    print("The guess number is less than 10")

The output is:

The guess number is greater than 15

This goes to show that the order you write your code is very important.

Example 3

guess_number = 32

if guess_number < 10:  #condition one
    print("The guess number is less than 10")
elif guess_number < 20:  #condition two
    print("The guess number is less than 20")
elif guess_number < 30:  #condition three
    print("The guess number is less than 30")
else:  #condition four
    print("The guess number is greater than 30")

The output is:

The guess number is greater than 30

Here you can notice that the if block evaluated to False and the multiple elif blocks also evaluated to False, so the else block executed instead.

Nested if statement

This is basically an if statement nested inside another if statement. It is used if a variable must be processed more than once i.e it has to satisfy multiple conditions to get the desired output. It can get pretty confusing after a while if you have too many conditions nested, so you want to try and keep the code as simple as possible even when you have to nest if statements. The syntax of a nested if statement is as follows:

if condition one:
   #Executes when condition one is true
   if condition two: 
      # Executes when both conditions one and two are true
   # End of condition two
# End of condition one

You can also nest if-else statements and if-elif-else statements. To find out more about nested if statements you can check out this resource.

The Pass statement

Conditional statements cannot be empty but if for some reason you have a conditional statement with no content, put in a pass statement to avoid getting errors. You can also use the pass statement in your code temporarily when you are writing your code, and you just need a placeholder till you write your actual code blocks. For example:

number = 3
if number < 10:
    pass

When you use the pass statement nothing actually happens when you run the code, but you avoid getting an error.

Conclusion

  • The if statement is a commonly used conditional statement which executes some code only if certain set conditions are met.

  • The if-else statements consist of the if block and else block, and indented code in the if block is executed if the conditions evaluate to True. If the conditions evaluate to False, the else block is executed. The else block doesn’t accept any conditions and it is an optional statement.

  • If-elif-else statement consist of three blocks - if, elif and else. The statement is used when we want only one branch of logic to ever execute and once one code block evaluates to be True and executes, no other code blocks after it execute even if they evaluate to be True. Elif stands for else if, and the code block cannot stand on its own so it is always chained to a precedence if block of code.

  • If statements can be nested inside one another, and this is used if a variable must be processed more than once i.e it has to satisfy multiple conditions to get the desired output.

  • If for some reason you have a conditional statement with no content, put in a pass statement to avoid getting errors. You can also use the pass statement in your code temporarily when you are writing your code to avoid errors as well.

Thank you for checking out my tutorial and I hope it has been very helpful to you. If you need some more resources on conditional statements in python you can check out this resource or this resource. See you soon!