Python If Statements

The if statement is probably the most well known statement in the world of computer programming. It allows you to make your program do something only if a given condition is true. You can also specify what should happen if the condition is false.

Basic if Example

Here's an example of a Python if statement in its simplest form:

Result
Well done, you passed the exam!

In this example, we assigned the number 56 to a variable called score. We then used an if statement to check if the value of the score variable is greater than 50. If it is, then we print out the text. If the score is lower, then we don't do anything (i.e. no text is printed out).

Basic else Example

You can also add an else part to your if statement, which allows you to specify what happens if the condition is false. In other words, you can make your program do one thing if the condition is true, and another thing if it's not.

Here's an example:

Result
Haha... you FAILED!

Basic elif Example

Going a step further, you can also add one or more elif parts to your statement. The elif parts are basically an "else if". In other words, they allow you to add extra conditions that are only tested if the previous if (or elif) was false.

Example using one elif:

Result
You failed... but heck... we'll hire you anyway!

Example using multiple elif lines:

Result
WTF... why on Earth do you wanna work here?

Remember the Colon

Note the use of the colon (:) at the end of the if, elif and else lines. This is required as part of the syntax.

Indenting

Note the use of indenting. In Python, indenting is an important part of the syntax. Python uses indenting to determine the grouping of statements.

Let's remove the indented line from the first example and see what happens:

Result
IndentationError: expected an indented block

An IndentationError. The Python interpreter didn't like it.

While you can get away with inconsistent indenting (for example, accidentally tabbing twice), it's best to try to keep the indenting consistent. This can help greatly with readability.

You can use either spaces or tabs for indentation, however it's best to use one or the other. Python 3 disallows mixing the use of tabs and spaces in some cases. Also, mixing tabs and spaces could cause issues when viewing the source code using a different text editor.

Use the Ternary Operator

We've already looked at the ternary operator when covering the Python operators, but in case you missed it, here it is again:

The condition (C) is evaluated first. If it returns True, the result is x, otherwise it's y.

Example:

Result
Low