If You Like It Then You Should Have Put a Ring on It: An Intro to Python Logic Part 2 – The If Statement

Hey guys!.

I hope you guys checked out that Pinterest cheat sheet on bools because today we’re going to build on what we went over on last time. The second part of Python logic is “The If Statement”.

So what is an if statement? It is simply a way for python to make decisions. For example if this is true, do this, if something else is true, do that.

There are a few keywords we need to know (actually there’s just three) before we can get started with creating if statements. So, as always, lets jump straight in!

The “If” in If Statements 

This part is pretty simple. The “if” part of an if statement is saying “if this is true then continue.” It looks like this:

  1. if x is this value:
  2.     Do this

Its important to include that colon at the end or else your program will crash. Also remember to indent the code under the if statement. This section is known as the body of the if statement and if it is not indented, it wont be executed by the if statement.

What “Else”?

The else keyword is exactly what it sound like. If something doesn’t fit the criteria in your if statement, it will execute the code located  in the body of the else statement.

  1. if x is this value:
  2.     Do this
  3. else:
  4.     Do this

This One’s Weird: “Elif”

Ok, this was a bit confusing to me when I learned it so I’m going to try my best. The elif keyword is basically a more specific else statement. For example:

  1. if x is this value:
  2.     Do this
  3. elif x is this other value:
  4.     Do this
  5. else:
  6.     Do this

It’s almost like another if statement in side your if statement, which is actually something you can do. It looks like this:

  1. if x is this value:
  2.     if y is this other value:
  3.         Do this

The reason for the elif keyword is to avoid unnecessary indentation. It can get hard to keep track of all those indents, so to avoid putting code in the wrong places, we use the elif statements.

So What Can I Put in an If Statement

Any thing that results in a boolean value can be put in an if statement. For example:

  • if x == True:
  • if y > x:
  • if 17%4 > 139/x:
  • if not(True and False) or not(True) or False:

This also applies to the elif keyword.

A Few Things To Remember

It’s important to remember that an if statement can have an infinite number of elif keywords in it, but only one else keyword is allowed. Also, the else keyword cannot have anything directly to the right of it other than a colon.

Alright guys, that’s pretty much it. I’ll see you in the next one.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.