If Statements

If Statements

Selection is one of three main constructs of programming (along with Sequence and Iteration). An if statement is a conditional statement that performs a certain action based on conditional values. Essentially, if thing A is true, then thing B will happen.

Screenshot 2016-08-30 at 11.05.14 AM

If the user answers yes to this question then an appropriate statement is printed. Remember that all commands in Python are lowercase (if / input / print etc.). The double equals stands for ‘is equal to‘. The colon stands for THEN and the line after an if statement must be indented (press tab key once).

Screenshot 2016-08-30 at 12.01.39 PM

But what if the window is not open? At the moment nothing will happen if you type no:

Screenshot 2016-08-30 at 12.03.02 PM

The elif command stands for ‘else if’. Essentially: If thing A is true then do thing thing B, else if thing C is true then do thing D:

Screenshot 2016-08-30 at 11.30.45 AM

But what about any other answer than yes or no? The else command will submit a response if the value is anything else:

Screenshot 2016-08-30 at 11.34.00 AM

The if and elif commands have a colon at the end, but else has it at the start. Also, else does not need to be on a new line.

Screenshot 2016-08-30 at 12.05.06 PM

Practice Task 1

Nested If Statements

Complex programs may require you to have if statements within if statements! When something is within another thing in Python, it is nested. You must ensure that the related if, elif and else statements line up with each other.

screenshot-repl-it-2016-11-05-21-39-21

One possible output for this program is:

screenshot-repl-it-2016-11-05-21-39-40

Practice Task 2

Selection not working? Tick off these common errors:

Correct colon placement?
Have you indented properly?
Is elif and else in line with if?
Double equals sign?
Speech marks for a string?

< Back to Section Four