How do I write an if statement?

An if statement, also called a "conditional", is a means to allow a code fragment to execute only under specific circumstances. This kind of conditionality is common in every day life - for example:

  1. You take an umbrella out with you if it is raining and
  2. You can only buy a pint of beer in a pub if your age is 18 or over

Python examples

Here are these simple examples converted into Python:

if isRaining():

This example is quite abstract, because we are assuming that somebody else has implemented functions for isRaining() and takeUmbrella(). Slightly less abstract:

if age >= 18:

General examples

The general form of a simple if statement is as follows:

if <condition>:

The <condition> part is a boolean expression that specifies when the code in <statements> should execute: if <condition> is true, they will. If <condition> is false, they will not.

In the umbrella example, we used a function as the boolean expression - the function isRaining() must return True or False (based on whether it's raining or not). In the beer example, we compared a variable called "age" with the value 18 - again, whether age is greater than 18 will be either true or false.

Writing if statements

To formulate your own if statement, you need to understand:

  • What condition you are testing. To determine whether your condition is appropriate (whether it is a "boolean expression"), you need to ask yourself whether the condition you have used is a question with a yes/no answer.
  • What should happen if that condition is true.

Tiny case study

Let's imagine we have a variable storing somebody's name and we only say hello to people called "Peter". Here, the condition is based on whether the variable name matches some preset value. We can express this as the boolean expression:


This "question" has a yes/no answer - either the variable "name" matches "Peter" or it doesn't. We use this condition in our if statement as follows:

if name=="Peter":
    print "hello there".

Using if-else

We can extend if statements also allow us to have code that executes if the condition is *not* true. Again these happen in every day life:

  • If I have any milk, I'll eat cereal. Otherwise I'll buy something on the way to work.
  • If it's Friday, I'll drink beer. Otherwise, I'll drink coke.

Here are these as examples:

if haveMilk():
if day=="friday":

As before, the boolean statements are yes/no questions. The statements beneath the if are what we do if the answer is "yes". The statements below the else are what we do if the answer is no.

More help

There are many more examples and (yet more) explanation of if statements to be found here. This also covers the elif part, which allows you to have more than one condition.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License