Custom Search

Python: if _ _ _ _: elif: _ _ _ _ else: _ _ _ _

The syntax for the alternative action instruction is:

if (conditions): 

indented block of actions

else: 

indented block of actions

 

It is very useful bit of code as it allows the computer to take alternative actions depending on conditions.

Note the colons - miss them out and you will have an error!

 

The computer chooses which block of actions to execute in this way.

First the computer checks the conditions after the 'if'.

If they are true, the computer then executes the block of code (the indented instructions) belonging to the 'if' part.

If the conditions are false, the computer ignores the indented block after the 'if' and instead executes the 'else' indented block of instructions.

The indentation is needed to know which instructions belong to which part of the command.

Afterwards the computer continues executing the non-indented instructions in the program.

If you want to have more than one alternative you use elif - contracted version of 'else if'

Multiple Alternative Action

The syntax for the multiple alternative action instruction is:

if (conditions): 

indented block of actions

elif (conditions):

indented block of actions

else: 

indented block of actions

Note that the order in which you write the conditions is important, because the computer checks them from top to bottom and executes only one block, for the first condition that is true.

The else block has no condition, so it's a 'catch all' in case no condition is true.

This means you have to be very careful to put condition checks in such an order that should the first one not apply it will then go to the next one - not jump directly to 'else'.

See this example