Skip main navigation

Conditional statements

this video gives an overview of how to use the if, elif, and else keywords to create conditional statements.
4.2
A conditional flow in Python means that the program has a branching structure that allows it to react differently depending on specified conditions. When writing code in Python, you define this branching structure with if, elif and else statements. Let’s look at how these statements work. Imagine you are travelling along a road and you come to an intersection with three other roads branching off. How do you decide which road to take? Perhaps you could ask yourself, how do you feel? If you feel hungry, you should go to the shop to buy some food. An if statement evaluates a condition using Boolean logic. It checks if the statement is True. Usually the statement involves comparing a variable against a value or another variable.
52.9
It might be equal, not equal, greater than or less than, for instance. If the statement is True, the program executes each indented line under the if statement in sequence. Consider the scenario again. If you don’t feel hungry, but you do feel sick, you should go to the doctor to find out what’s wrong. An elif, short for else if statement, is useful here. You can create as many elif statements as you want to cover every other condition. Each elif statement has its own set of actions to take when its condition is True. Back to our example. If you feel anything else, maybe tired or bored, you should probably go home.
97.1
An else statement acts as a catch-all option for any other condition that your code doesn’t address. It can be the default. Once you master, if, elif and else statements, you can do so much more with Python. Let’s get going.

This video explained how to use the if, elif, and else keywords to create conditional statements.

Until this point, you have only worked with programs that run sequentially: lines of code executed one by one. You don’t have to do anything special for this to happen – it’s the default way of processing code. But as you learned in the video, code can also have conditional structure: a section of code only executes if a specified condition is met.

Previously, you learned that comparison operators evaluate either True or False based on the relationship and Boolean logic. However, Python has if, else, and elif statements that let you set conditions and choose the next step according to those conditions. Like a Boolean variable or relationship between two values, these statements can have a True or False value as well. When the statement has a True condition, the program executes the associated steps. As a result, these statements, or conditionals, are very helpful for decision-making in programming.

if/else statements

The syntax of the if/else statement is:

if test_condition:
statement(s)
else:
statement(s)

In the following code example, Python checks if the password is correct or incorrect:

password = '1234'
if password == '1234':
print('password is correct')
else:
print('password is incorrect')

Output:

password is correct

You can see upfront that the password is ‘1234’. If the password is 1234, the output must be ‘password is correct’, and if it is anything other than 1234, the output must be ‘password is incorrect’. Try to change the string value assigned to the password variable and see how the output changes.

Take note of the white spaces in the code. These indentations are not just there to make the code more readable. They indicate to the Python interpreter that the indented section is part of a code block subordinate to the else, if, or other type of statement. Make sure that you have four spaces or a tab space before each line in the if or else block.

elif statement

There is also an elif (else if) statement used frequently in Python. This is something like a second if statement; for example:

fruit = 'apple'
if fruit == 'orange':
print('I do not really like oranges')
elif fruit == 'apple':
print('apples are my favorite')
else:
print('hmm I might also like' + fruit)

Output:

apples are my favorite

As you can see from this example, the if block first checks whether ‘fruit’ is equal to ‘orange’. If it isn’t, the program moves on to elif. Since in the elif block ‘fruit’ is equal to ‘apple’, you get the corresponding message.

Try for yourself

  • Using the previous example, change the value of the fruit variable in the snippet to something other than ‘apple’ or ‘orange’. What happens to the output?
  • Now try adding an input() function at the beginning of the program so that the user can set the value of fruit each time the program runs.

‘and’ and ‘or’ logical operators

You can have multiple ‘if/else’ blocks in one program and you can also nest those ‘if/else’ inside one another. Hence, you can also have multiple conditions. To add those conditions, you use Boolean keywords such as and** and **or`.

Let’s look at a code example that uses the and operator:

first_name = 'Jane'
last_name = 'Doe'
if first_name == 'Jane' and last_name == 'Doe':
print('Welcome, ' + first_name + ' ' + last_name)
else:
print('User not recognised')

Output:

Welcome, Jane Doe

Basically, if first_name has the value ‘Jane’ and last_name has the value ‘Doe’ (the condition is True), the program prints ‘Welcome’ followed by the first and last names. Both conditions need to be met.

Try for yourself

  • Using the previous example, change the values of either first_name or last_name. What happens to the output?
  • Now try adding two input() functions at the beginning of the program to capture the first and last names. Try entering different combinations of incorrect and correct first and last names each time you run the program. How does the output change?

Next, let’s look at a code example that uses the or operator:

name = 'Carl'
if name == 'Carl' or name == 'Carlson':
print('Hello, ' + name)
else:
print('You are not Carl')

Output:

Hello, Carl

As you can see in the output, the or keyword returns True if one of the statements returns True. At least one condition needs to be met.

Try for yourself

  • Using the previous example, change the value of name to something else. What happens to the output?
  • Try adding more conditions to the if statement using or. How does the output change?
  • Now try adding an input() function at the beginning of the program to capture the name. Try entering different names each time you run the program. How does the output change?
  • Finally, go back to the and operator example. Change the and to an or operator in the if statement. Try inputting different combinations of correct and incorrect first and last names each time you run the program. How does the output change?

Additional reading

To learn more about these and other control flow statements in Python, refer to: More Control Flow Tools. [1]

References

    1. More Control Flow Tools — Python 3.9.7 documentation [Internet]. Python.org; [date unknown]. Available from: https://docs.python.org/3/tutorial/controlflow.html
This article is from the free online

Introduction to Programming with Python

Created by
FutureLearn - Learning For Life

Our purpose is to transform access to education.

We offer a diverse selection of courses from leading universities and cultural institutions from around the world. These are delivered one step at a time, and are accessible on mobile, tablet and desktop, so you can fit learning around your life.

We believe learning should be an enjoyable, social experience, so our courses offer the opportunity to discuss what you’re learning with others as you go, helping you make fresh discoveries and form new ideas.
You can unlock new opportunities with unlimited access to hundreds of online short courses for a year by subscribing to our Unlimited package. Build your knowledge with top universities and organisations.

Learn more about how FutureLearn is transforming access to education