What’s an elif in Python? [Answered with vids and gifs]

In short,  an “elif”  means “else  if”.. If you’ve used other programming languages, you’re probalby used to writing else if  or elseif , but python contracts that to the single word elif  .

 

The video below, from our middle school cu
rriculum
for teaching kids python, explains how to use an elif

 

 

If  you’re not a video person, here’s the “cliff notes”:

So, when do you use  an elif ?

Well, to answer that question, you must first understand when to use an if/else statement.

When to use an if/else statement in Python

 

As you can see in the above picture, an if/else is meant for two distinct cases. In the  above example, our penguin either deals  with case 1 ( penjee.isFish(right) )  or case 2

Rules for using elif

Elif Rules in Python

As the above picture shows, and elif  is sandwiched in between the initial if  and the final else, and you can have as many elif  conditions as you want!

The animation below shows how the order of execution works in an elif  .

if-elif-if_control_flow