Selection (IF...)

So far, all the programs we have written have been linear.

That means they start at the beginning, then step-by-step each instruction is followed until it gets to the end. There is a clear sequence to each statement.

Sometimes though we want our programs to be able to do different things. We might need to get the program to make a decision and select a different path to follow.

The IF... ELSE... statement

Python makes use of and IF statement and comparative statements to make decisions.

Take a look at this program...

What do you think it does?
What would happen if you type in the answer yes?
What would happen if you type in the answer no?

Try the program out in Python and see if your predictions are correct.
When you copy the program be very careful...

Look out for...

  • the colons :

  • the indents

The flow diagram below shows the 2 paths that the program could take
based on the result of the comparative statement 'answer == yes'.
If the statement is true it follows one path, else it is false and follows another path...

Watch the video below to see how to use the IF statement

pythonSelection.mp4

Key Words

Comparative Operator

A symbol that is used to ask the computer to compare two values. It will return a boolean value stating if the expression is true or false.

Selection Statement

A programming structure that is used to choose what happens next in a program. Relies on a conditional statement being true.