Python 4a - 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.
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:
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:
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.
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.”
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.
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.