Python Crash Course
)}

# "elif‍" Statements

`if-else` statements are used to manage which parts of your code will get executed based on a single condition. `elif` statements allow you to test more than one condition.

let's look back at the example from the previouse article:

``````‍grocery_items = {﻿'bananas'﻿: 2.99﻿, 'apples'﻿: 1.29﻿, 'papayas'﻿: 2.39﻿}
item = 'brussel sprouts'

if (item in grocery_items)﻿:
print﻿(﻿'The item exists'﻿)
else﻿:
print﻿(﻿'The item does not exist'﻿)‍``````

`>‍> The item exists`

let's assign item a price value:

``‍item, price = 'brussel sprouts'﻿, 3.99``

‍Now we're going to use the `elif` statement to see if the price is too expensive. You should end up with something like this:

``````‍grocery_items = {﻿'bananas'﻿: 2.99﻿, 'apples'﻿: 1.29﻿, 'papayas'﻿: 2.39﻿}
item, price = 'brussel sprouts'﻿, 3.99

if (item in grocery_items)﻿:
print﻿(﻿'The item exists'﻿)
elif (price > 2.99﻿)﻿:
print﻿(﻿'The price is too expensive'﻿)
else﻿:
print﻿(﻿'The item does not exist'﻿)‍``````

`‍>> The price is too expensive`

Let's explain what happened above:

1. We've got two values `item` and `price`
2. The first `if` statement checks if the item is `grocery_items`. In our case it wasn't. So the elif is activated.
3. The `elif` checks if the price is higher than `2.99`. In our case, it was, so the code inside of it executes.
4. The `else` statement is ignored, since the above condition was executed.

‍This is the first time we've ever used a comparison operator `>` in a control flow statement `if` or `elif`.

Let's look at another example where we use the `==` operator:

``````daytime = 'dawn'

if daytime == 'dawn'﻿:
print﻿(﻿'still asleep'﻿)
elif daytime == 'morning'
print﻿(﻿'time to go to work'﻿)
elif daytime == 'noon'﻿:
print﻿(﻿'time to take a lunch break'﻿)
elif daytime == 'afternoon'﻿:
print﻿(﻿'time to go home'﻿)
else﻿:
print﻿(﻿'time to sleep'﻿)``````

`‍>> still asleep`

Since the value of daytime above is `dawn`, `still asleep` will be printed.

Now what happens when we change daytime to `**noon**`?

The console should print: `>> time to take a lunch break`

‍And if we change `**daytime**` to `**very late at night**`?

The `else` statement should execute, and the console should output:

`>> time to sleep`

So the purpose of this exercise was not only use the `elif` statements but also for you to remember to use double equal signs `==` when making a comparison.‍

Do not confuse the single equal sign `=` with the double equal sign `==`.

• If you would like to make a comparison, use the double equal sign `==`
• if you wish to assign a value, use the single equal sign `=`

Feedback Summary
4.8
8 students
5

75%
4

25%
3

0%
2

0%
1

0%
Written Reviews
There are no written reviews yet.