Skip main navigation

Conditional statements

this video gives an overview of how to use the if, elif, and else keywords to create conditional statements.

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

Reach your personal and professional goals

Unlock access to hundreds of expert online courses and degrees from top universities and educators to gain accredited qualifications and professional CV-building certificates.

Join over 18 million learners to launch, switch or build upon your career, all at your own pace, across a wide range of topic areas.

Start Learning now