Python 4a - If Statements 

If Statements

Selection is one of three primary constructs of programming, along with Sequence and Iteration.

An if statement is a conditional statement that performs a specific action based on conditional values.

 

Essentially, if thing A is true, then thing B will happen.

If the user answers yes to the window question, then an appropriate statement is printed.

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).

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

py1.png

The elif command stands for else if.

 

Essentially: If thing A is true then do thing B, else if thing C is true then do thing D:

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

 

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.

py2.png
py3.png
py4.png

Practice Task 1

1. Write an input line to ask a user whether they want to take the red pill or the blue pill.

2. If they write “red” then print “You stay in wonderland and see how far the rabbit hole goes”.

3. Elif they write “blue” then print “You wake up in your bed and believe what you want to believe.”

4. Else print “That’s not an option Neo.”

Example solution:

py5.PNG

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 make sure that the related if, elif and else statements line up with each other. Use the tab key to indent a line.

py7.png

=

py8.png

Practice Task 2

1. Write your own program with if, elif and else statements.

2. Have at least one nested option, with a further question and if statement. Use the weather example above to help you. Make sure you keep all associated if, elif and else statements in line with each other.

py8.PNG

Example solution:

Using Selection with Numbers

Mathematical operators such as > (greater than) >= (greater than or equal to) < (less than) and <= (less than or equal to) can be used with if statements.

 

Logical operators such as and and or can also be used - more about them in the next section.

When comparing a variable's value to a specific number, such as 50, don't forget to use double equals.

selection1.png