Python if, elif, else statements

post front image representing code

The if, elif, and else statements are all there to allow for decision making in python and other programming languages as well.

Let's look at a simple if statement code:

a_bool = True

if a_bool == True:
  print("Yay, it worked!")

Try running it, see what happens! Try tweaking it, and see how it will affect the result 🙂

Now let's figure out what's happening

a_bool = True

Here we assign a boolean value (true of false/ 1 or 0) True to a variable a_bool.

if a_bool == True:

Next we check for a_bool to a have the value true

  print("Yay, it worked!")

and if the check passes, "Yay, it worked!" prints out on our screen.


Now since an if statement simply checks for something to be true instead of writing

if a_bool == True:

we can write

if a_bool:

and the result will still be the same


Now what if you want some other code to run in case some other condition is met? elif does it

a_bool = False
other = True

if a_bool == True:
  print("Yay, it worked!")
elif other:
  print("Something else worked")

I've modified our a_bool variable so the if won't run but the elif will as I added another variable that the elif is checking. Try it out, play with it 🙂


Let's say none of the conditions are met, and you have code you want to run in that case as well. That's a job for else

a_bool = False
other = False

if a_bool == True:
  print("Yay, it worked!")
elif other:
  print("Something else worked")
else:
  print("Nothing worked, so this has to work")

Now the else will run as I've changed the other variable to false as well. Again, try it out, and play with it.


Hopefully you've learned something, if you have, please feel free to share this post 🙂

Leave a Reply

Your email address will not be published.